|
Hello all,
I'm currently writing a java program that allows a user to input a name that is then saved to a .txt file. It works fine if I run the program once but when I run the program again it adds the data to the same line. Is there a way I can make the program add the names to a new line of text in the .txt file. My program has multiple classes, belows is only the one that actually writes to to the file. Thanks in advance
public class MyAppend
{
public void MyDisplay()
{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String userName = null;
try {
userName = br.readLine();
//this is where the user inputs his name
} catch (IOException ioe) {
System.out.println("IO error trying to read your name!");
System.exit(1);
}
String Name = userName;
//this is what the input will be known as to the program
try
{
PrintWriter out = new PrintWriter(
new FileOutputStream("/forum/thetext.txt", true));
out.print(Name);
out.close();
//here the program saves the name to the text file. I either want it to start a new line everytime it writes something
}
catch (IOException e)
{
System.out.println(e);
}
}
[/qoute]
|
|
|
Two choices:
1 - read the entire file, saving what you read, add the name as desired and then write it all back to the file. Every time you open a file and write to it the writing starts at the beginning and writes over all that is there.
2 - use a RandomAccessFile in which you can preset the amount of space available for multiple entries. Then access the desired space and overwrite it.
|
|
|
Try:
new FileOutputStream("thetext.txt\n", true));
Hope it works.
|
|
|
|
|
|
|
|