0

Im trying to add a list of words taken off the end user Via a JOptionPane input menu and store them in a text file without overwriting whats already there. eg of the txt file

bell cool hello now java compile

The problem I have is that it keeps overwriting what I have Any help??

  import javax.swing.JDialog;
  import java.util.Arrays;
  import javax.swing.*;
import java.util.*;
import java.io.*;

public class write
{
public static void main(String [] args) throws IOException
{
    PrintWriter out = new PrintWriter(aFileWriter);
 String word = JOptionPane.showInputDialog(null, "Enter a word");
  out.print(word);



  out.close();
  aFileWriter.close();
 }
 }

ok so now its appending the file but not moving to a new line for a new word??

2 Answers2

2

Use another constructor for FileWriter that provides the 'append' argument:

FileWriter aFileWriter = new FileWriter("mydata.txt", true );
Andy Thomas
  • 84,978
  • 11
  • 107
  • 151
  • Thank you very much but how would I make the program skip to a new line for every word? –  Mar 26 '13 at 22:12
  • You could use `out.println(word)` – SeKa Mar 26 '13 at 22:23
  • An easy way is to use out.println(word) rather than out.print(word). Welcome to StackOverflow, by the way. If you like this answer best, you can click the checkmark to its left. – Andy Thomas Mar 26 '13 at 22:25
0

Open the file:

PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter("outfilename", true)));

Append the string to the file:

out.println("the text");

Close file:

out.close();

Better explanation.

Community
  • 1
  • 1
gkiko
  • 2,283
  • 3
  • 30
  • 50