tags:

views:

158

answers:

3

I want to print the content of a simple text file in Java exactly the way the text appears in the text file.

The print out has the same content as the text file but the format is not the same. Tabs and line breaks are ignored in the print out. Any help will be very much appreciated.

A: 

FileUtils.readFileToString(file) should do (from commons-io), but be careful with larger files, because they may take up the whole memory that's allocated for the VM.

Another thing you can use is IOUtils.copy(new FileInputStream(..), outputStream); - this will transfer everything from one stream (a file stream in this case) to another, output stream.

Bozho
+1  A: 

As @Joachim Sauer and @bmargulies indicated, without more details, we can't really tell you exactly what the problem is.

But to give you something to contrast your code with, the following will read a file provided as an argument and then read it char-by-char (i.e. it supports unicode characters), printing that character out as it goes. If this doesn't accomplish your goal, a specific (small) example of input that fails for you would be nice.

import java.io.*;
class printout {
   public static void main (String[] args) {
      if (args.length < 1) {
         System.err.println ("Usage: printout <filename>");
         System.exit (1);
      }

      File sourceFile = new File (args[0]);
      FileReader fr = null;
      try {
         fr = new FileReader (sourceFile);
         int inChar;

         while ( (inChar = fr.read()) != -1 ) {
            System.out.printf ("%c", inChar);
         }
      } catch (IOException e) {
         System.err.printf ("Failure while reading %s: %s\n",
                            args[0], e.getMessage());
         e.printStackTrace ();
      } finally {
         try {
            if (fr != null) { fr.close (); }
         } catch (IOException e) {
            System.err.printf ("Error closing file reader: %s\n",
                               e.getMessage());
            e.printStackTrace ();
         }
      }
   }
}
RTBarnard
<code>if (args.length ");</code>?
James McMahon
1.) Don't use HTML tags to format code 2.) that doesn't read byte-by-byte, it reads character-by-character.
Joachim Sauer
@Joachim Sauer: Thanks for the pointing out my error about char-by-char reading rather than byte-by-byte; I've corrected the answer text accordingly.
RTBarnard
A: 

With printing you mean this? Then try replacing all \t with e.g. 4 spaces and \n with new drawString calls.

Another possibility is to fill a JTextComponent or JEditorPane and print it.

If you meant normal sys-out-printing then see the answer of RTBarnard + use:

BufferedReader reader = new BufferedReader(
    new InputStreamReader(new FileReader("file.txt"), "UTF-8");
reader.readLine(); etc

This is easier in my eyes and you will always use the correct encoding

Karussell