mur7ay
mur7ay

Reputation: 833

Writing to files and I/O

I'm trying to write a program that gets a users input that is then written to an output file called userStrings.txt. I'm also trying to stop the processing once the user inputs 'done', but I'm not sure how to accomplish this.

Here is my code:

import java.io.*;
import java.util.Scanner;

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


    // Name of the file
        String fileName = "userStrings.txt";

        Scanner scan = new Scanner(System.in);

        try {
            // FileReader reading the text files in the default encoding.
                FileWriter fileWriter = new FileWriter("userStrings.txt");

            // Wrapping FileReader in BufferedReader.
                BufferedWriter bufferedWriter = new BufferedWriter(fileWriter);

                bufferedWriter.write("A string");
                bufferedWriter.write("Another string");
                bufferedWriter.write("Yet more text...");
                System.out.println("Enter something, DONE to quit: ");
                String input = scan.nextLine();

            // Closing file
                bufferedWriter.close();
        }

        catch (IOException ex){
            System.out.println("Error writing to file " + "userStrings.txt" + "");
        }


    } // End of method header
} // End of class header

In order to write to a file, do I still use System.out.println? and is the bufferedWriter.write even necessary? I'm just trying to understand the I/O and writing to files better.

Thanks!

Upvotes: 0

Views: 386

Answers (2)

Krikor Ailanjian
Krikor Ailanjian

Reputation: 1852

Right under you take input from the console, run a while loop to test that input is not equal to "done". Inside the while loop, add input to your file and get the next line of input.

while(!input.toLowerCase().Equals("done"))
{
    bufferedWriter.write(input);
    input = scan.nextLine();
}

Upvotes: 0

Stephen C
Stephen C

Reputation: 719679

In order to write to a file, do I still use System.out.println?

No. That writes to standard output, not to your file.

If you are using println then you need to wrap your BufferedWriter with a PrintWriter. (Look at the javadocs for the System class where the out field is documented.)

and is the bufferedWriter.write even necessary?

If you are going to write directly to the BufferedWriter then yes, it is necessary, though you probably need to an appropriate "end of line" sequence. And that's where it gets a bit messy because different platforms have different native "end of line" sequences. (If you use PrintWriter, the println method picks the right one to use for the execution platform.)

I'm also trying to stop the processing once the user inputs 'done', but I'm not sure how to accomplish this.

Hint: read about the Scanner class and System.in.

Upvotes: 3

Related Questions