Java Tutorial #4 Combining reading and writing functions

in #java9 years ago

Previous tutorial https://steemit.com/java/@nicetea/java-tutorial-3-reading-files-with-bufferedreader-and-printing-out-line-numbers

This time, we are reading a files contents, adding line numbers and writing the result to a file.

The code(Explanation below):

    public static void main(String[] args) {
        LineNumberReader f;
        String line;
        PrintWriter p;
        try {
            f = new LineNumberReader(new FileReader("steemit.txt"));
            p = new PrintWriter("steemit-new.txt");
            while ((line = f.readLine()) != null)
                p.println(f.getLineNumber() + ": " + line);
            p.flush();
            f.close();
            p.close();
        } catch (IOException e) {
            System.out.println("Error while reading");
        }
    }

Firstly, we are again declaring a few variables at the beginning.
Inside the try{ we are creating a new LineNumberReader, which will make it a little easier for us, to read the line numbers. Next we are creating a PrintWriter, which will be used to print out the results achieved from the LineNumberReader.
Inside the while(, we are printing a new line to the PrintWriter with 1.) the line number and 2.) the actual contents of the line.
Lastly, we are closing the files and handling an error as usual.

The output of "steemit-new.txt" should look like this
Selection_018.png

Stay tuned!

Coin Marketplace

STEEM 0.04
TRX 0.32
JST 0.081
BTC 61426.98
ETH 1631.00
USDT 1.00
SBD 0.42