Java: how to write formatted output to plain text file

前端 未结 6 1707
粉色の甜心
粉色の甜心 2021-01-18 18:24

I am developing a small java application. At some point i am writing some data in a plain text file. Using the following code:

Writer Candidateoutput = null;         


        
相关标签:
6条回答
  • 2021-01-18 19:03

    Window's Notepad needs \r\n to display a new-line correctly. Only \n is ignored by Notepad.

    0 讨论(0)
  • 2021-01-18 19:14

    Well Windows expects a newline and a carriage return char to indicate a new line. So you'd want to do \r\n to make it work.

    0 讨论(0)
  • 2021-01-18 19:15

    You can use line.separator system property to solve your issue.

    E.g.

    String separator = System.getProperty("line.separator");
    
    Writer Candidateoutput = null;
    File Candidatefile = new File("Candidates.txt"),
    Candidateoutput = new BufferedWriter(new FileWriter(Candidatefile));
    Candidateoutput.write(separator + " Write this text on next line");
    Candidateoutput.write("\t This is indented text");
    Candidateoutput.close();
    

    line.separator system property is a platform independent way of getting a newline from your environment.

    0 讨论(0)
  • 2021-01-18 19:19

    You would have to use the Java utility Formatter which can be found here: java.util.Formatter

    Then all you would have to do is create an object of Formatter type such as this:

    private Formatter output; 
    

    In this case, output will be the output file you are writing to.

    Then you have to pass the file name to the output object like this:

    output = new Formatter("name.of.your.file.txt")
    

    Once that's done, you can either hard-code the file contents to your output file using the output.format command which is similar to the System.out.println or printf commands.

    Or use the Scanner utility to input the data into memory then use output.format to output this data to the output object or file.

    This is an example on how to write a record to output:

    output.format( "%d %s %s %2f\n" , field1.decimal, field2.string, field3.string, field4.double)
    

    There is a little bit more to it than this, but this sure beats parsing data, or using a bunch of complicated third party plugins.

    To read this file you would redirect the Scanner utility to read a file instead of the console:

    input = new Scanner(new File( "name.of.your.file.txt") 
    
    0 讨论(0)
  • 2021-01-18 19:23

    A PrintWriter does this platform independent - use the println() methods.

    0 讨论(0)
  • 2021-01-18 19:28

    Use System.getProperty("line.separator") for new lines - this is the platform-independent way of getting the new-line separator. (on windows it is \r\n, on linux it's \n)

    Also, if this is going to be run on non-windows machines, avoid using \t - use X (four) spaces instead.

    0 讨论(0)
提交回复
热议问题