Is this java i/o code acceptable?

I was told to create a program that reads data from txt file, then sorts data based on < or > 0 and writes data to 2 different txt files. I've achieved my goal but I want to make sure there isn't a better way I could do it. The teacher mentioned BufferedReader(?).

---------------------------------------------------------

import java.util.Scanner;

import java.io.*;

public class Transactions

{

public static void main (String[] args) throws IOException

{

String line, name, file = "Transactions.txt";

File openFile = new File (file);

Scanner inFile = new Scanner (openFile);

PrintWriter posFile = new PrintWriter ("Deposits.txt");

PrintWriter negFile = new PrintWriter ("Withdrawals.txt");

while (inFile.hasNext())

{

double number = inFile.nextDouble();

System.out.println(number);

if (number < 0) negFile.print (number + " \r\n");

if (number > 0) posFile.print (number + " \r\n");

}

System.out.println("Deposits.txt and Withdrawal.txt files have been created.");

inFile.close();

negFile.close();

posFile.close();

}

}

Comments

  • If you want to use Scanner, that takes FileReader. Scanner won't know what to do with a File. See link to an example below.

    You should note that you can only have one Scanner open at a time. Note also that you can only have one stream open at a time ... the output or the input -- that is, if you are reading or writing files. You program as is will be printing the results to the Terminal window.

    Lastly, Java doesn't need "\r\n"; Java is smart enough to see what OS you are running the program on and 'most of the time' will put in the correct line ending. Java is happy with just "\n".

  • It's a very good way! no need to change it !

Sign In or Register to comment.