开发者

Printing the exact content of a text file in Java

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开发者_JAVA百科 and line breaks are ignored in the print out. Any help will be very much appreciated.


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


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


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜