Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Import Textfile and read line by line in Java

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!

like image 457
Jeff Avatar asked Aug 08 '10 03:08

Jeff


People also ask

How do you read a line from a text file in Java?

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.

How do I read a file line by line?

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.

How do you read the second line of a text file in Java?

//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.


2 Answers

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();
}
like image 176
Stephen C Avatar answered Sep 30 '22 15:09

Stephen C


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

like image 31
Tansir1 Avatar answered Sep 30 '22 16:09

Tansir1