Tutorial :Reading and displaying data from a .txt file



Question:

How do you read and display data from .txt files?


Solution:1

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();  


Solution:2

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.


Solution:3

In general:

  • Create a FileInputStream for the file.
  • Create an InputStreamReader wrapping the input stream, specifying the correct encoding
  • Optionally create a BufferedReader around the InputStreamReader, 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.


Solution:4

I love this piece of code, use it to load a file into one String:

File file = new File("/my/location");  String contents = new Scanner(file).useDelimiter("\\Z").next();  


Solution:5

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 + "'");      }  }  

}


Solution:6

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);  

:-)


Solution:7

To read lines from .txt file with encoding UTF-8:

File krokiPath = new File("Records\Record");  BufferedReader in = new BufferedReader(          new InputStreamReader(new FileInputStream(krokiPath), "UTF8"));    while((r = in.readLine()) != null) {      System.out.println(r);  }  in.close();  


Solution:8

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();      }    }  


Solution:9

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);  }  


Solution:10

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.


Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
Previous
Next Post »