954,518 Members — Technology Publication meets Social Media
Username:
Password:
Lost login information?
Have something to say? Contribute New Article Reply to this Article

Writing to a file

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

im_desperate
Newbie Poster
20 posts since Nov 2007
Reputation Points: 10
Solved Threads: 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

indienick
Junior Poster in Training
71 posts since Aug 2005
Reputation Points: 23
Solved Threads: 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

im_desperate
Newbie Poster
20 posts since Nov 2007
Reputation Points: 10
Solved Threads: 1
 

This question has already been solved

Post: Markdown Syntax: Formatting Help
You