I was wondering how one would go about importing a text file. I want to import a file and then read it line by line.
thanks!
We can use java. io. BufferedReader readLine() method to read file line by line to String. This method returns null when end of file is reached.
Method 1: Read a File Line by Line using readlines() readlines() is used to read all the lines at a single go and then return them as each line a string element in a list. This function can be used for small files, as it reads the whole file content to the memory, then split it into separate lines.
//read the file, line by line from txt File file = new File("train/traindata. txt"); FileReader fr = new FileReader(file); BufferedReader br = new BufferedReader(fr); String line; line = br. readLine(); while(line != null) { lines = line.
I've no idea what you mean by "importing" a file, but here's the simplest way to open and read a text file line by line, using just standard Java classes. (This should work for all versions of Java SE back to JDK1.1. Using Scanner is another option for JDK1.5 and later.)
BufferedReader br = new BufferedReader(
new InputStreamReader(new FileInputStream(fileName)));
try {
String line;
while ((line = br.readLine()) != null) {
// process line
}
} finally {
br.close();
}
This should cover just about everything you need.
http://download.oracle.com/javase/tutorial/essential/io/index.html
And for a specific example: http://www.java-tips.org/java-se-tips/java.io/how-to-read-file-in-java.html
This might also help: Read text file in Java
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With