0

Hey
i have to write a program that will prompt the user to write sentences and those sentences will be written until the user type "stop".
i though of doing such a thing but its not doing what i want because i want each input to be on a new line.

import java.io.*;

public class Writing{
    public static void main(String [] args)
    {
    try{
       File file = new File("mytext.txt");
       PrintWriter out =
            new PrintWriter(
                new BufferedWriter(
                    new FileWriter(file, true)));  
                }
                catch (IOException e)
		{
			System.err.println ("Unable to write to file");
			System.exit(-1);
            }

        }
    }

and also another thing i dont know how to finish writing to the text file.

Thanks in advance

2
Contributors
2
Replies
5
Views
9 Years
Discussion Span
Last Post by im_desperate
1

I haven't written any I/O Java code in a while, but I do remember using java.io.PrintStream which is a buffered stream, so you don't need to create a whole mess of inline class instances.

import java.io.*;
import java.util.Scanner;
...
try {
  PrintStream ps = new PrintStream(new File("file.txt"));
  Scanner s = new Scanner(System.in);
  String lineBuffer;
  
  lineBuffer = s.nextLine();
  
  ps.println(lineBuffer);
} catch (IOException ioex) {
  ...
} finally {
  ps.close();
  s.close();
}
return;
...

You may want to refine this code a little, and cover any other exceptions that may be thrown; I just wrote this out quickly and don't have time to check it, but it should work.

I haven't added any of your particulars into this, and for this I apologize, but I'm sure you can do it quite easily. :D

Votes + Comments
I like you're signature! I also agree with your solution hehe
0

thanks for the code
but actually the main thing that i wanted was someone to help me find a way when the user types a specific word to stop the program.
thanks in advance

This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.