Ok, I know this is a really rookie question, but I looked around online a lot and am yet unable to find the answer to my question:
How can I read input from a file line by line in java?
Assume a file input that has integers on each line, like:
1
2
3
4
5
Here's the snippet of code I am trying to work with:
public static void main(File fromFile) {
BufferedReader reader = new BufferedReader(new FileReader(fromFile)开发者_JS百科);
int x, y;
//initialize
x = Integer.parseInt(reader.readLine().trim());
y = Integer.parseInt(reader.readLine().trim());
}
Presumably, this would read in the first two lines and store them as integers in x and y. So going off the example, x=1, y=2.
It is finding a problem with this, and I don't know why.
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();
}
}
}
please check your main method()
. It should be like these
public static void main(String... args) {
}
or
public static void main(String[] args) {
}
then read like that :
BufferedReader reader = new BufferedReader(new FileReader(fromFile));
String line;
while( (line = reader.readLine()) != null){
int i = Integer.parseInt(line);
}
We usually use a while loop, the readLine
method tells whether the end of file is reached or not:
List<String> lines = new ArrayList<String>();
while ((String line = reader.readLine()) != null)
lines.add(line);
Now we have a collection (a list) that holds all lines from the file as separate strings.
To read the content as Integers, just define a collection of integers and parse while reading:
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
}
}
精彩评论