Export text file and added names in the text field - java

My code is when user type in the Name text filed, it will export as text file and record the Name.
For example,
I typed 1st time "James" in the Name text filed, it will appear
"James" in the text file. I type second time "Agnes" , it appears
"Agnes" in the text file. But It only appear one name in the text
file.
I want all the names appear whatever user type in the text filed.
How do i modify my codes?
try
{
new JTextField();
// create new file
String path="C:\\export.txt";
File file = new File(path);
// if file doesnt exists, then create it
if (!file.exists())
{
file.createNewFile();
}
FileWriter fw = new FileWriter(file.getAbsoluteFile());
BufferedWriter bw = new BufferedWriter(fw);
// write in file
// bw.write(txtName.getText());
if (txtName.getText() ==null)
{
bw.write(txtName.getText());
bw.write('\n');
System.out.print("1st Name:" +txtName.getText());
}
else
if (txtName.getText()!=null)
{
// bw.write('\n');
bw.write(txtName.getText());
System.out.print("2nd Name:" +txtName.getText());
}
// close connection
bw.flush();
bw.close();
fw.close();
}
catch(Exception e)
{
System.out.println(e);
}
Please advise.Thanks

You should use append mode when write file, like:
FileWriter fw = new FileWriter(file.getAbsoluteFile(), true);

Edit again:
FileWriter fileWritter = new FileWriter(file.getName(),true);
BufferedWriter bw = new BufferedWriter(fileWritter);
if (txtName.getText()!=null){
//this line edited
bw.write(txtName.getText()+"\n");
System.out.print("2nd Name:" +txtName.getText());
}

Related

Adding new lines of text in a text file

My app records sounds. Once the sound is recorded, user is asked to input a new file name. Now what I'm trying to do next is to add all file names in a text file so that I can read it later as an array to make a listview.
This is the code:
//this is in onCreate
File recordedFiles = new File(externalStoragePath + File.separator + "/Android/data/com.whizzappseasyvoicenotepad/recorded files.txt");
if(!recordedFiles.exists())
{
try {
recordedFiles.createNewFile();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
//this executes everytime text is entered and the button is clicked
try {
String content = input.getText().toString();
FileWriter fw = new FileWriter(recordedFiles.getAbsoluteFile());
BufferedWriter bw = new BufferedWriter(fw);
bw.write(">" + content + ".mp3");
bw.close();
} catch (IOException e) {
e.printStackTrace();
}
Now the problem is that everytime I record a new file, the previous line is overwritten. So if I record two files 'text1' and 'text2', after I've recorded text1, the txt file will show text1, but after I recorded the text2, the text2 will overwrite the text1 instead of inserting a new line.
I tried adding:
bw.NewLine()
before
bw.write(">" + content + ".mp3");
but it doesn't work.
If I record three sounds and name them sound1, sound2 and sound3, I want this to be the result:
>sound1
>sound2
>sound3
Use FileWriter constructor with boolean append argument
FileWriter fw = new FileWriter(recordedFiles.getAbsoluteFile(), true);
// ^^^^
this will let file append text at the end instead overwriting previous content.
You can do it by adding line.separator Property
bw.write(">" + content + ".mp3");
bw.write(System.getProperty("line.separator").getBytes());
Replace
FileWriter fw = new FileWriter(recordedFiles.getAbsoluteFile());
Instead of
FileWriter fw = new FileWriter(recordedFiles.getAbsoluteFile(), true);
FileWriter takes a boolean if it should overwrite. So use true if you would like to to append to the file instead of overwrite.

Saving to a specific directory

I'm currently trying to save a newly created text file to a directory that the user specifies. However, I don't see how it is possible with this code setup. Where does one specify where file is to be saved?
if(arg.equals(Editor.fileLabels[1])){
if(Editor.VERBOSE)
System.err.println(Editor.fileLabels[1] +
" has been selected");
filedialog = new FileDialog(editor, "Save File Dialog", FileDialog.SAVE);
filedialog.setVisible(true);
if(Editor.VERBOSE){
System.err.println("Exited filedialog.setVisible(true);");
System.err.println("Save file = " + filedialog.getFile());
System.err.println("Save directory = " + filedialog.getDirectory());
}
File file = new File("" + filedialog.getName());
SimpleFileWriter writer = SimpleFileWriter.openFileForWriting(filedialog.getFile() + ".txt");
if (writer == null){
System.out.println("Failed.");
}
writer.print("" + this.editor.getTextArea().getText());
writer.close();
}
FileChooser and FileWriter make things fairly easy, here is the java tutorial:
http://download.oracle.com/javase/tutorial/uiswing/components/filechooser.html
http://www.abbeyworkshop.com/howto/java/writeText/index.html
You call it like this:
JFileChooser fc = new JFileChooser();
int returnVal = fc.showOpenDialog(aComponent);
if (returnVal == JFileChooser.APPROVE_OPTION)
{
File toSave = fc.getSelectedFile();
FileWriter outWriter = new FileWriter(toSave);
PrintWriter outPrinter = new PrintWriter(outWriter);
outPrinter.println("" + this.editor.getTextArea().getText());
}
else
{
//user pressed cancel
}
Remember that it is the PrintWriter class that does the actual printing.
EDIT:
If you want the user to select directories only, call
fc.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
before displaying it. Note that in this case you will have to specify a new File object WITHIN that directory in order to be able to write text to it (attempting to write the text to a directory will result in an IOException).
writer.print("" + this.editor.getTextArea().getText());
Don't use methods like that. All text components support a write(...) method. All you have to do is get the File name that you want to write the file to.
Something like:
JtextArea textArea = new JTextArea(....);
....
FileWriter writer = new FileWriter( "TextAreaLoad.txt" ); // get the file name from the JFileChooser.
BufferedWriter bw = new BufferedWriter( writer );
textArea.write( bw );
bw.close();
If you don't know how to use file choosers then read the section from the Swing tutorial on How to Use File Choosers.

Create a file based on conditions

How to write a program in Java to check the existence of a txt file if does not exist than create a new one else append the new txt in that file.
FileWriter fstream = new FileWriter("foo.txt",true);
BufferedWriter out = new BufferedWriter(fstream);
out.write("foo bar");
out.close();
The second argumnet to FileWriter tells it to append.

Java FileWriter - Append Line of Text File

I have a button in a GUI, and when the button is pressed the user has the ability to add information to a text file. I have this part setup fine, but the thing that is messing with me is that when the user writes to the file it erases all the info in the text file and the only line left is the new one that was just added. I need to add the information and still keep the original info in the text file. I thought the append command was able to do this, but I'm obviously doing something wrong. Any help would be awesome!
Here's my code:
FileWriter fWriter = null;
BufferedWriter writer = null;
try {
fWriter = new FileWriter("info.txt");
writer = new BufferedWriter(fWriter);
writer.append(javax.swing.JOptionPane.showInputDialog(this, "add info"));
writer.newLine();
writer.close();
} catch (Exception e) {
}
Use the constructor that takes a bool append parameter. See the javadocs for FileWriter for that.
fWriter = new FileWriter("info.txt", true);
You need writer.flush(). PrintWriter are auto flush by default but not Writers

How do you append to a text file instead of overwriting it in Java?

I am trying to add a line to a text file with Java. When I run my program, I mean to add a simple line, but my program is removing all old data in the text file before writing new data.
Here is the code:
FileWriter fw = null;
PrintWriter pw = null;
try {
fw = new FileWriter("output.txt");
pw = new PrintWriter(fw);
pw.write("testing line \n");
pw.close();
fw.close();
} catch (IOException ex) {
Logger.getLogger(FileAccessView.class.getName()).log(Level.SEVERE, null, ex);
}
Change this:
fw = new FileWriter("output.txt");
to
fw = new FileWriter("output.txt", true);
See the javadoc for details why - effectively the "append" defaults to false.
Note that FileWriter isn't generally a great class to use - I prefer to use FileOutputStream wrapped in OutputStreamWriter, as that lets you specify the character encoding to use, rather than using your operating system default.
Change this:
fw = new FileWriter("output.txt");
to this:
fw = new FileWriter("output.txt", true);
The second argument to FileWriter's constructor is whether you want to append to the file you're opening or not. This causes the file pointer to be moved to the end of the file prior to writing.
Use
fw = new FileWriter("output.txt", true);
From JavaDoc:
Constructs a FileWriter object given a
File object. If the second argument is
true, then bytes will be written to
the end of the file rather than the
beginning.
Two options:
The hard way: Read the entire file, then write it out plus the new data.
The easy way: Open the file in "append" mode: new FileWriter( path, true );

Categories