Read the content of a fileTag(s): IO


From a Java application
This following example is for an application.
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.InputStreamReader;

public class Cat  {
   public static void main (String args[]) throws Exception {
      String line;
      FileInputStream fin = null;
      BufferedReader br = null;
      InputStreamReader isr = null;

      try {
         fin =  new FileInputStream("D:/temp/howto.txt");
         isr = new InputStreamReader(fin);
         br = new BufferedReader(isr);
         while ((line = br.readLine()) != null) {
            System.out.println(line);
         }
      }
      finally {
         if (br != null)  br.close();
         if (isr != null) isr.close();
         if (fin != null) fin.close();
      }
   }
}

The following method read a data file and return the content as a String. We use a StringBuffer to optimize string concatenation operations.

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;


public class Cat  {

   public static final String EOL = System.getProperty("line.separator");

   private static String readFile(String filename) throws IOException {
      BufferedReader br = null;
      FileReader fr = null;

      try {
         fr = new FileReader(filename);
         br = new BufferedReader(fr);
         String nextLine = "";
         StringBuilder sb = new StringBuilder();
         while ((nextLine = br.readLine()) != null) {
           sb.append(nextLine); // note: BufferedReader strips the EOL character
                                //   so we add a new one!
           sb.append(EOL);
         }
         return sb.toString();
      }
      finally {
         if (br != null) br.close();
         if (fr != null) fr.close();
      }
   }

   public static void main (String args[]) throws Exception {
      System.out.println(readFile("d:/temp/howto.txt"));
   }
}

JDK1.5 provides the java.util.Scanner class which can be used to quickly read a file.

The delimeter "\Z" represents the end-of-file marker.

import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;

public class QuickFileRead {
  public static void main(String[] args) throws FileNotFoundException {
    Scanner scanner =
      new Scanner(new File("c:/temp/text.txt")).useDelimiter("\\Z");
    String contents = scanner.next();
    System.out.println(contents);
    scanner.close();
  }
}

JDK7+ provides, with the NIO package, a new way to get all the content of file quickly. You don't need to close anything because readAllLines() is taking care of that.

import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.List;

public class Cat  {

   public static void main (String args[]) throws Exception {
      Path path = Paths.get( "d:/temp/howto.txt" );
      List <String> lines = Files.readAllLines(path, StandardCharsets.UTF_8);
      for (String element : lines) {
         System.out.println(element);
       }
   }
}

See this HowTo to read a File stored in a JAR.


From a Java applet (deprecated)

With an Applet, we can only open file on the same server that the Applet is coming from.

import java.applet.*;
import java.net.*;
import java.io.*;
public class MyApplet extends Applet {
  public void init() {
    readFile("mydatafile.txt");
  }
  public void readFile(String f) {
    try {
      String aLine = "";
      URL source = new URL(getCodeBase(), f);
      BufferedReader br =
        new BufferedReader
          (new InputStreamReader(source.openStream()));
      while(null != (aLine = br.readLine())) {
         System.out.println(aLine);
      }
      br.close();
      }
    catch(Exception e) {
      e.printStackTrace();
    }
  }
}

The next Applet reads a data file and inserts the data in a Choice component.

import java.applet.*;
import java.awt.*;
import java.net.*;
import java.io.*;

public class ReadDataInChoice extends Applet {
  Choice myChoice;

  public void init() {
    myChoice  = new java.awt.Choice();
    add(myChoice);
    readFile("dataforchoice.txt");
  }
  public void readFile(String f) {
    try {
      String anItem = "";
      URL source = new URL(getCodeBase(), f);
      BufferedReader in =
         new BufferedReader(new InputStreamReader(source.openStream()));
      while(null != (anItem = in.readLine())) {
        myChoice.add(anItem);
      }
      in.close();
    }
    catch(Exception e) {
     e.printStackTrace();
    }
  }
}

[dataforchoice.txt]

item 1
item 2
item 3
item 4
item 5
ITEM 6
Try it here.

blog comments powered by Disqus