Java: how to write formatted output to plain text file

前端 未结 6 1708
粉色の甜心
粉色の甜心 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: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") 
    

提交回复
热议问题