Results 1 to 4 of 4

Thread: How to let Java read text file line by line.

  1. #1
    Join Date
    Jul 2009
    Posts
    1,118

    How to let Java read text file line by line.

    Hi,

    I am trying to run a java program that will read the text file line by line.
    Is there any sample code available? I am learning DataInputStream class.

    Thanks in adavance.

  2. #2
    Join Date
    Oct 2008
    Posts
    100

    Re: How to let Java read text file line by line.

    Java Read File Line by Line

    Class DataInputStream
    A data input stream is use to read primitive Java data types from an underlying input stream in a machine-independent way. An application uses a data output stream to write data that can later be read by a data input stream.

    BufferedReader

    Read text from a character-input stream, buffering characters so as to provide for the efficient reading of characters, arrays, and lines.

    The buffer size may be specified, or the default size may be used. The default is large enough for most purposes.

    In general, each read request made of a Reader causes a corresponding read request to be made of the underlying character or byte stream. It is therefore advisable to wrap a BufferedReader around any Reader whose read() operations may be costly, such as FileReaders and InputStreamReaders. For example,

    BufferedReader in
    = new BufferedReader(new FileReader("foo.in"));


    will buffer the input from the specified file. Without buffering, each invocation of read() or readLine() could cause bytes to be read from the file, converted into characters, and then returned, which can be very inefficient.

    Programs that use DataInputStreams for textual input can be localized by replacing each DataInputStream with an appropriate BufferedReader.

    Code:
    import java.io.*;
    class FileRead 
    {
       public static void main(String args[])
      {
          try{
        // Open the file that is the first 
        // command line parameter
        FileInputStream fstream = new FileInputStream("textfile.txt");
        // Get the object of DataInputStream
        DataInputStream in = new DataInputStream(fstream);
            BufferedReader br = new BufferedReader(new InputStreamReader(in));
        String strLine;
        //Read File Line By Line
        while ((strLine = br.readLine()) != null)   {
          // Print the content on the console
          System.out.println (strLine);
        }
        //Close the input stream
        in.close();
        }catch (Exception e){//Catch exception if any
          System.err.println("Error: " + e.getMessage());
        }
      }
    }

  3. #3
    Join Date
    May 2008
    Posts
    33

    Re: How to let Java read text file line by line.

    Reading and writing text files :

    * it is almost always a good idea to use buffering (default size is 8K)
    * it is often possible to use references to abstract base classes, instead of references to specific concrete classes
    * there is always a need to pay attention to exceptions (in particular, IOException and FileNotFoundException)


    Commonly used items :

    * BufferedReader - readLine
    * BufferedWriter - write + newLine
    * Scanner - allows reading files in a compact way

    The FileReader and FileWriter classes always use the system's default character encoding. If this default is not appropriate (for example, when reading an XML file which specifies its own encoding), the recommended alternatives are, for example :

    FileInputStream fis = new FileInputStream("test.txt");
    InputStreamReader in = new InputStreamReader(fis, "UTF-8");

    FileOutputStream fos = new FileOutputStream("test.txt");
    OutputStreamWriter out = new OutputStreamWriter(fos, "UTF-8");

    Scanner scanner = new Scanner(file, "UTF-8");

    Code:
    import java.io.*;
    
    public class ReadWriteTextFile {
    
      /**
      * Fetch the entire contents of a text file, and return it in a String.
      * This style of implementation does not throw Exceptions to the caller.
      *
      * @param aFile is a file which already exists and can be read.
      */
      static public String getContents(File aFile) {
        //...checks on aFile are elided
        StringBuilder contents = new StringBuilder();
        
        try {
          //use buffering, reading one line at a time
          //FileReader always assumes default encoding is OK!
          BufferedReader input =  new BufferedReader(new FileReader(aFile));
          try {
            String line = null; //not declared within while loop
            /*
            * readLine is a bit quirky :
            * it returns the content of a line MINUS the newline.
            * it returns null only for the END of the stream.
            * it returns an empty String if two newlines appear in a row.
            */
            while (( line = input.readLine()) != null){
              contents.append(line);
              contents.append(System.getProperty("line.separator"));
            }
          }
          finally {
            input.close();
          }
        }
        catch (IOException ex){
          ex.printStackTrace();
        }
        
        return contents.toString();
      }
    
      /**
      * Change the contents of text file in its entirety, overwriting any
      * existing text.
      *
      * This style of implementation throws all exceptions to the caller.
      *
      * @param aFile is an existing file which can be written to.
      * @throws IllegalArgumentException if param does not comply.
      * @throws FileNotFoundException if the file does not exist.
      * @throws IOException if problem encountered during write.
      */
      static public void setContents(File aFile, String aContents)
                                     throws FileNotFoundException, IOException {
        if (aFile == null) {
          throw new IllegalArgumentException("File should not be null.");
        }
        if (!aFile.exists()) {
          throw new FileNotFoundException ("File does not exist: " + aFile);
        }
        if (!aFile.isFile()) {
          throw new IllegalArgumentException("Should not be a directory: " + aFile);
        }
        if (!aFile.canWrite()) {
          throw new IllegalArgumentException("File cannot be written: " + aFile);
        }
    
        //use buffering
        Writer output = new BufferedWriter(new FileWriter(aFile));
        try {
          //FileWriter always assumes default encoding is OK!
          output.write( aContents );
        }
        finally {
          output.close();
        }
      }
    
      /** Simple test harness.   */
      public static void main (String... aArguments) throws IOException {
        File testFile = new File("C:\\Temp\\blah.txt");
        System.out.println("Original file contents: " + getContents(testFile));
        setContents(testFile, "The content of this file has been overwritten...");
        System.out.println("New file contents: " + getContents(testFile));
      }
    }

  4. #4
    Join Date
    May 2008
    Posts
    41

    Re: How to let Java read text file line by line.

    This code will read the MyFile.txt and print its content on the console. It reads the file line by line in the form of DataInputStream.

    Code:
    import java.io.BufferedInputStream;
    import java.io.DataInputStream;
    import java.io.File;
    import java.io.FileInputStream;
    import java.io.FileNotFoundException;
    import java.io.IOException;
    
    /**
     * This program reads a text file line by line and print to the console. It uses
     * FileOutputStream to read the file.
     * 
     */
    public class FileInput {
    
      public static void main(String[] args) {
    
        File file = new File("C:\\MyFile.txt");
        FileInputStream fis = null;
        BufferedInputStream bis = null;
        DataInputStream dis = null;
    
        try {
          fis = new FileInputStream(file);
    
          // Here BufferedInputStream is added for fast reading.
          bis = new BufferedInputStream(fis);
          dis = new DataInputStream(bis);
    
          // dis.available() returns 0 if the file does not have more lines.
          while (dis.available() != 0) {
    
          // this statement reads the line from the file and print it to
            // the console.
            System.out.println(dis.readLine());
          }
    
          // dispose all the resources after using them.
          fis.close();
          bis.close();
          dis.close();
    
        } catch (FileNotFoundException e) {
          e.printStackTrace();
        } catch (IOException e) {
          e.printStackTrace();
        }
      }
    Source:

Similar Threads

  1. Read one line at a time using fgets in C
    By ElroyDJ in forum Software Development
    Replies: 6
    Last Post: 30-12-2011, 10:26 PM
  2. HELP - add new line in text file without format changed
    By newbie1818 in forum Software Development
    Replies: 2
    Last Post: 13-09-2011, 05:17 PM
  3. How to move to next line by PHP in text file?
    By Ramona19 in forum Software Development
    Replies: 4
    Last Post: 09-06-2011, 07:09 AM
  4. Assign each line of a text file to a variable
    By hitman126 in forum Operating Systems
    Replies: 1
    Last Post: 22-01-2011, 07:42 AM
  5. Bash Script, read without new line
    By Kieran in forum Software Development
    Replies: 2
    Last Post: 06-02-2009, 09:59 PM

Tags for this Thread

Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  
Page generated in 1,713,254,607.46473 seconds with 17 queries