Adding new lines of text in a text file - java

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.

Related

Saving JTable as a textfile

Im making a medical resource management system and i am using a text file to import the first set of Doctors. This is working fine and i have added the ability to remove a selected row, which is also working. However i want this change to become permanent and save on the text.
When i press my save button on the Java GUI i just clears the entire text file. I also have the ability the add separate doctors which is also working correctly. Any help would be appreciated. Below is my code for exporting the Jtable to the text file!
private void jButtonSaveActionPerformed(java.awt.event.ActionEventevt)
{
String filePath = "C:\\Users\\Stephen\\folder\\Programming
Assignment copy\\doctor.txt";
File file = new File(filePath);
try {
FileWriter fw = new FileWriter(file);
BufferedWriter bw = new BufferedWriter(fw);
for(int i = 0; i < jTableDoc.getRowCount(); i++){//rows
for(int j = 0; j < jTableDoc.getColumnCount(); j++){//columns
bw.write(jTableDoc.getValueAt(i, j).toString()+",");
}
bw.newLine();
}
bw.close();
fw.close();
} catch (IOException ex) {
Logger.getLogger(doctorTable.class.getName()).log(Level.SEVERE, null, ex);
} // TODO add your handling code here:
}

Java swing Save and Save as functions with JFileChooser

I am writing a little app and would like to add the same handler for two buttons: Save and Save As. For save if the file exists it should not open the JFileChooser,just save the content, but with my current code it always opens the dialog. How do I do this? Here's my code
public void actionPerformed(ActionEvent e) {
JComponent source = (JComponent)e.getSource();
if (pathToFile.length()>0){
File file = new File(pathToFile);
if (file.exists()){
try(FileWriter fw = new FileWriter(file.getName() + ".txt", true)){
fw.write(area.getText());
}
catch(Exception ex){
System.out.println(ex.toString());
}
}
}
else{
if (fchoser.showSaveDialog(source.getParent())== JFileChooser.APPROVE_OPTION){
try(FileWriter fw = new FileWriter(fchoser.getSelectedFile()+".txt")){
fw.write(area.getText());
f.setTitle(fchoser.getSelectedFile().getPath());
pathToFile = fchoser.getSelectedFile().getPath();
}
catch(Exception ex){
}
}
}
UPDATE Added code to check if file exsists. It does and there is no exception but the additional text does not write.
Not related to your question but:
fw.write(area.getText());
Don't use the write method of a FileWriter. This will always write the text to the file using a "\n" as the line separator which may or may not be correct for the OS your code is running on.
Instead you can use the write(...) method of the JTextArea:
area.write(fw);
Then the proper line separator will be used.

Export text file and added names in the text field

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());
}

How do I append text to a csv/txt file in Processing?

I use this simple code to write a few strings to the file called "example.csv", but each time I run the program, it overwrites the existing data in the file. Is there any way to append the text to it?
void setup(){
PrintWriter output = createWriter ("example.csv");
output.println("a;b;c;this;that ");
output.flush();
output.close();
}
import java.io.BufferedWriter;
import java.io.FileWriter;
String outFilename = "out.txt";
void setup(){
// Write some text to the file
for(int i=0; i<10; i++){
appendTextToFile(outFilename, "Text " + i);
}
}
/**
* Appends text to the end of a text file located in the data directory,
* creates the file if it does not exist.
* Can be used for big files with lots of rows,
* existing lines will not be rewritten
*/
void appendTextToFile(String filename, String text){
File f = new File(dataPath(filename));
if(!f.exists()){
createFile(f);
}
try {
PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter(f, true)));
out.println(text);
out.close();
}catch (IOException e){
e.printStackTrace();
}
}
/**
* Creates a new file including all subfolders
*/
void createFile(File f){
File parentDir = f.getParentFile();
try{
parentDir.mkdirs();
f.createNewFile();
}catch(Exception e){
e.printStackTrace();
}
}
You have to use a FileWriter (pure Java (6 or 7)) rather than PrintWriter from the Processing API.
FileWriter has a second argument in it's constructor that allows you to set a Boolean to decide whether you will append the output or overwrite it (true is to append, false is to overwrite).
The documentation is here: http://docs.oracle.com/javase/7/docs/api/java/io/FileWriter.html
Note you can also use a BufferedWriter, and pass it a FileWriter in the constructor if that helps at all (but I dont think it's necessary in your case).
Example:
try {
FileWriter output = new FileWriter("example.csv",true); //the true will append the new data
output.println("a;b;c;this;that ");
output.flush();
output.close();
}
catch(IOException e) {
println("It Broke :/");
e.printStackTrace();
}
As above, this will work in the PDE - and in Android - but if you need to use it in PJS, PyProcessing, etc, then you will have to hack it
dynamically read the length of the existing file and store it in an ArrayList
add a new line to the ArrayList
use the ArrayList index to control where in the file you are currently writing
If you want to suggest an enhancement to the PrintWriter API (which is probably based off of FileWriter), you can do so at Processing's Issue page on GitHub:
https://github.com/processing/processing/issues?state=open
Read in the file's data, append your new data to that, and write the appended data back to the file. Sadly, Processing has no true "append" mode for file writing.

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

Categories