every time the code runs i want the new record to be added to a new line
as it is when a new record is added it will write over previous line
private void writeFile() {
String FILENAME = g.getText();
String content = results;
FileOutputStream fos = null;
try {
fos = openFileOutput(FILENAME, MODE_PRIVATE);
fos.write(content.getBytes());
Toast.makeText(getApplicationContext(), "File Saved", 0).show();
} catch (IOException e) {
e.printStackTrace();
}
}
You need to write the "newline" character as well when writing data:
private void writeFile() {
String FILENAME = g.getText();
String content = results;
FileOutputStream fos = null;
try {
fos = new FileOutputStream(file);
fos.write(content.getBytes());
fos.write(System.getProperty("line.separator"));
} catch (IOException e) {
e.printStackTrace();
}
}
But be careful with writing binary data like this. It's better to use e. g. BufferedWriter to write string data:
BufferedWriter writer = new BufferedWriter(new FileWriter("filename"));
writer.write("Hello world!");
writer.newLine();
Related
This question already has answers here:
How to append text to an existing file in Java?
(31 answers)
Closed 7 years ago.
How can I write in existing .txt file? I've tried multiple approaches, I've stopped on this one:
private void writeToFile(String data) {
try {
File file = new File(infoDirectory, txtName);
FileOutputStream fOut = new FileOutputStream(file);
OutputStreamWriter myOutWriter = new OutputStreamWriter(fOut);
myOutWriter.append(data);
myOutWriter.close();
fOut.close();
}
catch (IOException e) {
Log.i("Debug", "File write failed: " + e.toString());
}
}
But instead of adding string to the file, it re-writes insides.
[UPDATE]
private void writeToFile(String data) {
try {
File file = new File(infoDirectory, txtName);
FileWriter append = new FileWriter(file, true);
BufferedWriter output = new BufferedWriter(append);
output.write(data);
}
catch (IOException e) {
Log.i("Debug", "File write failed: " + e.toString());
}
}
[WORKING CODE]
private void writeToFile(String data) {
try {
File file = new File(infoDirectory, txtName);
FileOutputStream fOut = new FileOutputStream(file,true);
OutputStreamWriter myOutWriter = new OutputStreamWriter(fOut);
myOutWriter.append(data);
myOutWriter.close();
fOut.close();
}
catch (IOException e) {
Log.i("Debug", "File write failed: " + e.toString());
}
}
You have to open the file in append mode, which can be achieved by using the
FileWriter(String fileName, boolean append) constructor.
Replace this line
FileOutputStream fOut = new FileOutputStream(file);
To
FileOutputStream fOut = openFileOutput("yourfile.txt", MODE_APPEND);
Hope it helps.
I'm new in java and there is a question about BufferedWriter and OutputStream closing.
I have some logic, where it is inconvenient to use try-with-resources:
public static void writeFile(String fileName, String encoding, String payload) {
BufferedWriter writer = null;
OutputStream stream = null;
try {
boolean needGzip = payload.getBytes(encoding).length > gzipZize;
File output = needGzip ? new File(fileName + ".gz") : new File(fileName);
stream = needGzip ? new GZIPOutputStream(new FileOutputStream(output)) : new FileOutputStream(output);
writer = new BufferedWriter(new OutputStreamWriter(stream, encoding));
writer.write(payload);
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
writer.close();
stream.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
So, i have to close all resources by myself. Should i close OutputStream AND BufferedWriter? Or it is ok to close just BufferedWriter?
Is everything ok with my code?
No, Leave it to Java, let it handle it:
public static void writeFile(String fileName, String encoding,
String payload) {
boolean needGzip = payload.getBytes(Charset.forName(encoding)).length > gzipZize;
File output = needGzip ? new File(fileName + ".gz")
: new File(fileName);
try (OutputStream stream = needGzip ? new GZIPOutputStream(
new FileOutputStream(output)) : new FileOutputStream(output);
BufferedWriter writer = new BufferedWriter(
new OutputStreamWriter(stream, encoding))) {
writer.write(payload);
} catch (IOException e) {
e.printStackTrace();
}
}
It is OK to just close the BufferedWriter. If you follow the Javadoc you will see that it closes all nested streams.
If you close BufferedWriter its stream will be closed too but BufferedWriter and OutputStream both implements Closeable. So if you want you can just use try with resource to handle the close for you
for example :
public static void writeFile(String fileName, String encoding, String payload) {
File output = new File(fileName);
try (OutputStream stream = new FileOutputStream(output);
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(stream, encoding))) {
writer.write(payload);
} catch (IOException e) {
e.printStackTrace();
}
}
Edit: Added getStream to check if it needs gzip stream or no
Note: This answer is just an "update" of your code, i'm not sure what are you trying to do in general, so it may not be the best solution for your program
public static void writeFile(String fileName, String encoding, String payload) {
try (BufferedWriter writer = new BufferedWriter(
new OutputStreamWriter(getStream(fileName, encoding, payload), encoding))) {
writer.write(payload);
} catch (IOException e) {
e.printStackTrace();
}
}
public static OutputStream getStream(String fileName, String encoding, String payload) throws IOException {
boolean needGzip = payload.getBytes(encoding).length > gzipZize;
File output = needGzip ? new File(fileName + ".gz") : new File(fileName);
return needGzip ? new GZIPOutputStream(new FileOutputStream(output)) : new FileOutputStream(output);
}
I have been trying to create a class called TextFileReaderWriter I want to use the getters and setters to read and write to a text file in such a way that I can call the class and the method from anywhere in the program by simply using setfileContents(somestring) and somestring = getfileContents() something like this
example:
TextFileReaderWriter trw = new TextFileReaderWriter();
trw.setfileContents(somestring); //this would write 'somestring' to the text file.
String somestring = trw.getfileContents(); //this would return 'somestring' from the text file.
Here's what I have so far but it writes nothing to the file:
public class TextFileReaderWriter extends Activity{
String fileContents;
Context context;
String TAG = "MYTAG";
public TextFileReaderWriter(String fileContents, Context context) {
this.fileContents = fileContents;
this.context = context;
}
public String getFileContents() {
return fileContents;
}
public void setFileContents(String fileContents) {
this.fileContents = fileContents;
FileOutputStream fos = null;
try {
fos = context.openFileOutput("UserInputStore", Context.MODE_PRIVATE);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
OutputStreamWriter osw = new OutputStreamWriter(fos);
try {
osw.write(fileContents);
Log.d(TAG, fileContents);
} catch (IOException e) {
e.printStackTrace();
}
}
}
You don't need the OutputStreamWriter--FileOutputStreamwill do the trick just fine.
//what you had before
FileOutputStream fos = null;
try {
fos = context.openFileOutput(filename, Context.MODE_PRIVATE);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
//use just the file output stream to write the data
//data here is a String
if (fos != null) {
try {
fos.write(data.getBytes());
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
Method to save data on disk :
protected static void saveDataOnDisk(String data) {
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
try {
ObjectOutput objectOutput = new ObjectOutputStream(byteArrayOutputStream);
objectOutput.writeObject(data);
byte[] buffer = byteArrayOutputStream.toByteArray();
File loginDataFile = (new File(filePath)); // file path where you want to write your data
loginDataFile.createNewFile();
FileOutputStream fileOutputStream = new FileOutputStream(loginDataFile);
fileOutputStream.write(buffer);
fileOutputStream.close();
objectOutput.flush();
objectOutput.close();
byteArrayOutputStream.flush();
byteArrayOutputStream.close();
Log.i(“SAVE”, ”———————-DONE SAVING”);
} catch(IOException ioe) {
Log.i(“SAVE”, “———serializeObject|”+ioe);
}
}
Method to fetch data from disk:
private static Object getDataFromDisk() {
try {
FileInputStream fileInputeStream = new FileInputStream(FilePath);
ObjectInputStream objectInputStream = new ObjectInputStream(fileInputeStream);
Object data = (Object) objectInputStream.readObject();
objectInputStream.close();
fileInputeStream.close();
return dataModel;
} catch (Exception error) {
Log.i(“FETCH”, ”—-getDataFromDisk———ERROR while reading|” + error);
}
return null;
}
private void saveFormActionPerformed(java.awt.event.ActionEvent evt) {
name = nameFormText.getText();
surname = surnameFormText.getText();
age = Integer.parseInt(ageFormText.getText());
stadium = stadiumFormText.getText();
Venues fix = new Venues();
fix.setName(name);
fix.setSurname(surname);
fix.setAge(age);
fix.setStadium(stadium);
File outFile;
FileOutputStream fStream;
ObjectOutputStream oStream;
try {
outFile = new File("output.data");
fStream = new FileOutputStream(outFile);
oStream = new ObjectOutputStream(fStream);
oStream.writeObject(fix);
JOptionPane.showMessageDialog(null, "File written successfully");
oStream.close();
} catch (IOException e) {
System.out.println(e);
}
}
This is what I have so far. Any ideas on what I could do with it to append the file if it's already created?
You have first to check if the file exists before, if not create a new one. To learn how to append object to objectstream take a look at this question.
File outFile = new File("output.data");
FileOutputStream fStream;
ObjectOutputStream oStream;
try {
if(!outFile.exists()) outFile.createNewFile();
fStream = new FileOutputStream(outFile);
oStream = new ObjectOutputStream(fStream);
oStream.writeObject(fix);
JOptionPane.showMessageDialog(null, "File written successfully");
oStream.close();
} catch (IOException e) {
System.out.println(e);
}
Using Java 7, it is simple:
final Path path = Paths.get("output.data");
try (
final OutputStream out = Files.newOutputStream(path, StandardOpenOption.CREATE,
StandardOpenOption.APPEND);
final ObjectOutputStream objOut = new ObjectOutputStream(out);
) {
// work here
} catch (IOException e) {
// handle exception here
}
Drop File!
Here is the code:
Thread clientThread = new Thread() {
#Override
public void run() {
try {
client = new Client();
quest = client.readFile();
Log.v("Client string", quest);
//File file = new File(myContext.getFilesDir(), "questionnaire.xml");
//BufferedWriter bw = new BufferedWriter(new FileWriter(file));
//bw.write(quest);
File tempFile = File.createTempFile("questionnaire", ".xml");
FileOutputStream fout = new FileOutputStream(tempFile);
PrintStream out = new PrintStream(fout);
out.println(quest);//InputStream stream = new ByteArrayInputStream(quest.getBytes("UTF-8"));
//getResources().op
try {
Serializer serializer = new Persister();
responseToQuestionnaire = serializer.read(ResponseToQuestionnaire.class, tempFile);
}
catch(Exception e) {}
Log.v("Let's seeeeee",responseToQuestionnaire.getQuestionnaireTemplate().toString());
} catch (Exception e1) {
e1.printStackTrace();
}
// try {
// OutputStreamWriter outputStreamWriter = new OutputStreamWriter(
// openFileOutput(currentQuestionnaire.getName(),
// Context.MODE_PRIVATE));
// outputStreamWriter.write(client.readFile());
// outputStreamWriter.close();
// } catch (IOException e) {
// Log.e("Exception", "File write failed: " + e.toString());
// }
}
};
clientThread.start();
The code throws a Null Pointer exception even when quest is a full length string that prints in log perfectly fine. I tried multiple ways of saving the file but SimpleXML doesn't serialize string... only XML files.
Buffered streams don't necessarily write the data until they have to. Try closing the output stream before you call the read() method.