如何在java中按行读取文件中的输入?
问题描述:
好吧,我知道这是一个真正的菜鸟问题,但我环顾四周网上很多,但我无法找到我的问题的答案:如何在java中按行读取文件中的输入?
我怎样才能从一个文件行逐行读取输入?
假设对每一行整数文件输入,如:
1
2
3
4
5
这里的代码我想与之合作的片段:
public static void main(File fromFile) {
BufferedReader reader = new BufferedReader(new FileReader(fromFile));
int x, y;
//initialize
x = Integer.parseInt(reader.readLine().trim());
y = Integer.parseInt(reader.readLine().trim());
}
据推测,这将在阅读前两行并将它们作为整数存储在x和y中。因此,举个例子,x = 1,y = 2。
它发现这个问题,我不知道为什么。
答
public static void main(String[] args) {
FileInputStream fstream;
DataInputStream in = null;
try {
// Open the file that is the first
// command line parameter
fstream = new FileInputStream("textfile.txt");
// Get the object of DataInputStream
in = new DataInputStream(fstream);
BufferedReader br = new BufferedReader(new InputStreamReader(in));
String strLine;
int x = Integer.parseInt(br.readLine());
int y = Integer.parseInt(br.readLine());
//Close the input stream
} catch (Exception e) {//Catch exception if any
System.err.println("Error: " + e.getMessage());
} finally {
try {
in.close();
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
答
请检查您的main method()
。它应该是这样的
public static void main(String... args) {
}
或
public static void main(String[] args) {
}
然后阅读这样的:
BufferedReader reader = new BufferedReader(new FileReader(fromFile));
String line;
while((line = reader.readLine()) != null){
int i = Integer.parseInt(line);
}
答
我们通常使用while循环,该readLine
方法告诉是否结束文件是否到达:
List<String> lines = new ArrayList<String>();
while ((String line = reader.readLine()) != null)
lines.add(line);
现在我们有一个集合(一个列表),它将文件中的所有行保存为单独的字符串。
阅读的内容为整数,只是定义整数的收集和分析,同时阅读:
List<Integer> lines = new ArrayList<Integer>();
while ((String line = reader.readLine()) != null) {
try {
lines.add(Integer.parseInt(line.trim()));
} catch (NumberFormatException eaten) {
// this happens if the content is not parseable (empty line, text, ..)
// we simply ignore those lines
}
}
你可以发布任何堆栈strace的? – lweller 2011-01-19 07:32:57
请详细说明当前代码的问题是什么。你有错误吗?这是否仅仅是这个事实,只能读取2行而不是5行?它不编译或不运行? – Nanne 2011-01-19 07:33:23