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

Recommended Answers

All 2 Replies

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

commented: I like you're signature! I also agree with your solution hehe +2

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

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.