我有一个包含列表的文本文件,每一行都有我需要插入新对象的数据。因此,数据看起来像somename=3000
或另一种带有斜杠data another type = 6000
的类型。
我有一个特殊的类"Item“,它有String
和int
变量。需要将数据插入其中。每个新对象都必须添加到ArrayList<Item>
中。
// Calculate the lines for next for each loop
int lineCount = 0;
while (sc.hasNextLine()) {
lineCount++;
sc.nextLine();
}
for (int i = 0; i < lineCount; i++) {
// creating the object
Item item = new Item();
// add item object to items ArrayList
items.add(item);
// add line to String variable lineToString,
while (scaner.hasNextLine()) {
String lineToString = scaner.nextLine();
sc.nextLine();
}
所以,我想,要做到这一点,我需要
我使用Scanner
读取文本文件。当我试图将scaner.nextLine
插入到String
中时,它不起作用;我的意思是它正在执行,但是变量字符串lineToString
没有文本文件中的行。
有人能帮我想一想如何更好地解决这个问题吗?也许有更简单的方法从对象中的文本文件行插入2种不同类型的数据,并将其放入ArrayList
中?文本文件中的每一行都有不同的数据,并且必须位于不同的对象中。
发布于 2018-06-30 08:32:59
您没有从文本文件中清楚地提到行格式。到目前为止,我假设您有文本文件,其中每一行如下
someone=140000
您正在尝试读取这些文本行,并将它们分别解析为Item
的一个对象,该对象包含一个String
属性(我假设您将其命名为name
)和一个int
属性(假设您将其命名为number
)。
如果是这样,您就不需要逐行读取文本文件并进一步处理它。有几种方法可以逐行读取文本文件。
BufferReader
这是一种非常常见且迄今为止最合适的读取文本文件的方法,以考虑性能。
List<Item> particulatItems = new ArrayList<>();
// using try-with-resource that will help closing BufferedReader by own
try (BufferedReader br = new BufferedReader(new FileReader(file))) {
String line;
while ((line = br.readLine()) != null) {
particularItems.add(processLine(line));
}
}
扫描仪
你也可以用Scanner
。
try (Scanner scanner = new Scanner(new File(fileName))) {
while (scanner.hasNext()) {
particularItems.add(processLine(line));
}
} catch (FileNotFoundException e) {
e.printStackTrace();
}
您应该将行处理逻辑提取为一个独立的函数。这是清洁编码的良好实践。
public static Item processLine(Strinng line) {
String[] tokens = line.split("=");
Item item = new Item(tokens[0], tokens[1]);
}
假设您将特定对象定义为Item
,并且正在填充此类型的List
public class Item {
String name;
int number;
public Item(String name, String numtxt) {
this.name = name;
this.number = Integer.parseInt(numtxt);
}
// setter getter
}
更多阅读:
发布于 2018-06-30 08:28:56
看起来您已经在下面的代码片段中扫描了完整的文件:
while (sc.hasNextLine()) {
lineCount++;
sc.nextLine();
}
在此之后,您将再次在for-循环中迭代,但使用相同的扫描器,它读取了最后一行,因此以下内容可能返回false:
while (scaner.hasNextLine())
我可能永远也进不了循环
在再次迭代行之前,您应该重新设置扫描器。也可以使用扫描仪以外的其他工具来计数行数。
发布于 2018-06-30 08:32:12
除了@Ashish Mishra提到的,您正在执行for循环中的第二个while循环,为什么?一个循环还不够吗?
int lineCount = 0;
while (sc.hasNextLine()) {
lineCount++;
String lineToString = sc.nextLine();
Item item = new Item();
//convert lineToString to item
items.add(item);
}
https://stackoverflow.com/questions/51116565
复制