How do you read and display data from .txt files?
9 Answers
BufferedReader in = new BufferedReader(new FileReader("<Filename>"));
Then, you can use in.readLine(); to read a single line at a time. To read until the end, write a while loop as such:
String line;
while((line = in.readLine()) != null)
{
System.out.println(line);
}
in.close();
If your file is strictly text, I prefer to use the java.util.Scanner
class.
You can create a Scanner
out of a file by:
Scanner fileIn = new Scanner(new File(thePathToYourFile));
Then, you can read text from the file using the methods:
fileIn.nextLine(); // Reads one line from the file
fileIn.next(); // Reads one word from the file
And, you can check if there is any more text left with:
fileIn.hasNext(); // Returns true if there is another word in the file
fileIn.hasNextLine(); // Returns true if there is another line to read from the file
Once you have read the text, and saved it into a String
, you can print the string to the command line with:
System.out.print(aString);
System.out.println(aString);
The posted link contains the full specification for the Scanner class. It will be helpful to assist you with what ever else you may want to do.

- 136,852
- 53
- 295
- 323
-
I always forget about Scanner, never having actually used it... Shame it takes a charset *name* though :( (And I'd recommend always explicitly specifying the charset) – Jon Skeet Apr 08 '09 at 19:08
-
Well, I am assuming the simplest possible scenario. Adding charsets in can get confusing. Usually you don't have to worry about it. – jjnguy Apr 08 '09 at 19:10
-
-
I very rarely want to make my code system-dependent, which is what happens if you omit the charset. If I *did* want to use the default charset, I'd do so explicitly (Charset.defaultCharset().name()) Character encodings are a pain, but the sooner they're understood the better IMO. – Jon Skeet Apr 08 '09 at 19:14
-
I guess I'd rather pander to what I think the question asker is looking for. He/she probably looking to make their code system-independent. – jjnguy Apr 08 '09 at 19:17
In general:
- Create a
FileInputStream
for the file. - Create an
InputStreamReader
wrapping the input stream, specifying the correct encoding - Optionally create a
BufferedReader
around theInputStreamReader
, which makes it simpler to read a line at a time. - Read until there's no more data (e.g.
readLine
returns null) - Display data as you go or buffer it up for later.
If you need more help than that, please be more specific in your question.

- 1,421,763
- 867
- 9,128
- 9,194
Below is the code that you may try to read a file and display in java using scanner class. Code will read the file name from user and print the data(Notepad VIM files).
import java.io.*;
import java.util.Scanner;
import java.io.*;
public class TestRead
{
public static void main(String[] input)
{
String fname;
Scanner scan = new Scanner(System.in);
/* enter filename with extension to open and read its content */
System.out.print("Enter File Name to Open (with extension like file.txt) : ");
fname = scan.nextLine();
/* this will reference only one line at a time */
String line = null;
try
{
/* FileReader reads text files in the default encoding */
FileReader fileReader = new FileReader(fname);
/* always wrap the FileReader in BufferedReader */
BufferedReader bufferedReader = new BufferedReader(fileReader);
while((line = bufferedReader.readLine()) != null)
{
System.out.println(line);
}
/* always close the file after use */
bufferedReader.close();
}
catch(IOException ex)
{
System.out.println("Error reading file named '" + fname + "'");
}
}
}

- 799
- 1
- 12
- 30
public class PassdataintoFile {
public static void main(String[] args) throws IOException {
try {
PrintWriter pw = new PrintWriter("C:/new/hello.txt", "UTF-8");
PrintWriter pw1 = new PrintWriter("C:/new/hello.txt");
pw1.println("Hi chinni");
pw1.print("your succesfully entered text into file");
pw1.close();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
BufferedReader br = new BufferedReader(new FileReader("C:/new/hello.txt"));
String line;
while((line = br.readLine())!= null)
{
System.out.println(line);
}
br.close();
}
}

- 3,887
- 1
- 23
- 34

- 1
- 1
-
1Hello and welcome to StackOverflow. Please take some time to read the help page, especially the sections named ["What topics can I ask about here?"](http://stackoverflow.com/help/on-topic) and ["What types of questions should I avoid asking?"](http://stackoverflow.com/help/dont-ask). And more importantly, please read [the Stack Overflow question checklist](http://meta.stackexchange.com/q/156810/204922). You might also want to learn about [Minimal, Complete, and Verifiable Examples](http://stackoverflow.com/help/mcve). – Ataur Rahman Munna Nov 16 '16 at 09:37
In Java 8, you can read a whole file, simply with:
public String read(String file) throws IOException {
return new String(Files.readAllBytes(Paths.get(file)));
}
or if its a Resource:
public String read(String file) throws IOException {
URL url = Resources.getResource(file);
return Resources.toString(url, Charsets.UTF_8);
}

- 2,283
- 2
- 20
- 38
If you want to take some shortcuts you can use Apache Commons IO:
import org.apache.commons.io.FileUtils;
String data = FileUtils.readFileToString(new File("..."), "UTF-8");
System.out.println(data);
:-)

- 6,853
- 2
- 26
- 25
You most likely will want to use the FileInputStream class:
int character;
StringBuffer buffer = new StringBuffer("");
FileInputStream inputStream = new FileInputStream(new File("/home/jessy/file.txt"));
while( (character = inputStream.read()) != -1)
buffer.append((char) character);
inputStream.close();
System.out.println(buffer);
You will also want to catch some of the exceptions thrown by the read() method and FileInputStream constructor, but those are implementation details specific to your project.

- 31,257
- 32
- 136
- 234
-
2inputStream.read() doesn't return a *character* - it returns a *byte* (as an int, admittedly, but they're very different things). To read text, you should be using a Reader. – Jon Skeet Apr 08 '09 at 19:08