我试图逐行保存文件的行:
number -> number
number -> number
number -> number
number -> number
等。等。
我已将文件保存为以下(在Netbeans中)
BufferedReader in = new BufferedReader(new FileReader("C:\\Users\\jon\\Desktop\\data.txt"));
String str=null;
ArrayList<String> lines = new ArrayList<String>();
while((str = in.readLine()) != null){
lines.add(str);
}
String[] graph = lines.toArray(new String[lines.size()]);
运行我的函数时出现此错误(代码是语法过去逐行存储文件):
线程中的异常&#34; main&#34; java.lang.ArrayIndexOutOfBoundsException: -1
在我的功能不同的地方。我假设这是一个问题,因为我正在存储我的文件,错了吗?为什么?
答案 0 :(得分:0)
所以你只想逐行阅读? 我使用的是文件和扫描仪,对于使用arraylist的数组也可能更容易。
导入你必须使用
import java.io.File;
import java.io.IOException;
import java.util.Scanner;
也使用throws IOException
File fileData = new File("C:\\Users\\jon\\Desktop\\data.txt");
ArrayList<String> readFile = new ArrayList();
if (f.exists() && f.isFile() ) {
Scanner sc = new Scanner(fileData);
while (sc.hasNext()) {
String line = sc.next();
readFile.add(line);
}
sc.close();
}
如果你想在文件中读取这个应该有用,但是你提到用数字读取它们,为了做到这一点,我们必须使用整数的arraylist,我们需要解读整数读取,这可以简单通过替换ArrayList<String> readFile = new ArrayList();
完成
与ArrayList<Integer> readFile = new ArrayList();
并readFile.add(line);
与readFile.add(Integer.parseInt(line));
我希望这会帮助你。