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.
Related
Description:
In the code below What am i doing wrong in the code below, in my code audit i got improper resource shutdown or release.
I tried taking out the close and flush from the code below
File someFile = new File(fileName);
fos = new FileOutputStream(someFile);
fos.write(data);
fos.flush();
fos.close();
Main code:
FileOutputStream fos=null;
try {
Hashtable hash = responseBlob.getAllAttachments();
Enumeration e = hash.elements();
while (e.hasMoreElements()) {
SBADataAttach tmpAttach = (SBADataAttach) e.nextElement();
String tag = tmpAttach.getTag();
byte[] data = tmpAttach.getData();
// encode compressed file
if (hasTag(tag))
mimeResponse.addPart(tag, Base64.encodeBytes(data)
.getBytes());
else
mimeResponse.addPart(tag, data);
try {
if (this.configData.getBlobPath() != null)
{
// save compressed file
String fileName = File.separatorChar + "tmp"
+ File.separatorChar + tag;
Log.theLogger.debug("XisServlet.process() ... "
+ "Save compressed file = " + fileName);
File someFile = new File(fileName);
fos = new FileOutputStream(
someFile);
fos.write(data);
fos.flush();
fos.close();
}
} catch (Exception zipe) {
Log.theLogger.error(zipe.getMessage(), zipe);
}
}
} catch (SBADataException sde) {
// cannot detach files from blob
Log.theLogger.error(sde.getMessage(), sde);
}
finally {
try {
if( fos!=null ) {
fos.close();
}
} catch(IOException e) {
Log.theLogger.error(e.getMessage(), e);
}
}
I don't get any error. But in the Appsec finding i getImproper Resource Shutdown or Release
try{
//open resources
File someFile = new File(fileName);
fos = new FileOutputStream(someFile);
fos.write(data);
}
catch(Exception e1){
//handle exception
}finally{
//close resources
fos.flush();
fos.close();
}
}
I have declared variable directory as a global and using that variable below in my returnData method nut it is returning null value.
public void SaveImage(String FileName, Bitmap mBitmap) {
if (!Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
String root = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES).toString();
File directory = new File(root + File.separator + "HMS_BARCODE");
directory.mkdirs();
//create a file to write bitmap data
File f = new File(directory, FileName + ".png");
Log.e("dir", "" + directory);
try {
f.createNewFile();
} catch (IOException e) {
e.printStackTrace();
Log.e("IOException", "IOException");
}
//Convert bitmap to byte array
ByteArrayOutputStream bos = new ByteArrayOutputStream();
mBitmap.compress(Bitmap.CompressFormat.PNG, 0, bos);
byte[] bytearray = bos.toByteArray();
//Write bytes in file
FileOutputStream fos = null;
try {
fos = new FileOutputStream(f);
fos.write(bytearray);
fos.flush();
fos.close();
} catch (Exception e) {
e.printStackTrace();
Log.e("Exception", "" + e);
}
} else {
String root = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES).toString();
directory = new File(root + File.separator + "HMS_BARCODE");
if (!directory.exists()) {
directory.mkdirs();
}
File f = new File(directory, FileName + ".png");
Log.e("dir1", "" + directory);
try {
f.createNewFile();
} catch (IOException e) {
e.printStackTrace();
Log.e("IOException", "IOException");
}
Log.e("dir1", "" + directory);
//Convert bitmap to byte array
ByteArrayOutputStream bos = new ByteArrayOutputStream();
mBitmap.compress(Bitmap.CompressFormat.PNG, 0, bos);
byte[] bytearray = bos.toByteArray();
//Write bytes in file
FileOutputStream fos = null;
try {
fos = new FileOutputStream(f);
fos.write(bytearray);
fos.flush();
fos.close();
} catch (Exception e) {
e.printStackTrace();
Log.e("Exception", "" + e);
}
}
}
// this is method returning null value I want want that directory
// value to pass to another class
public File returnData() {
Log.e("Exception", "" + directory);
return directory;
}
Please format your question correctly, it is hard to read. From what I can see your directory variable is not global, it is local for saveImage method.
If you want to have access to the directory variable from different methods of the same class instance, then you need to declare it as a class variable. For example:
public class MyClass {
private File directory;
public void saveImage(...) {....}
public File returnData(...) {...}
}
You must call SaveImage method in your returnData method :
//this is method returning null value i want want that directory value to pass to another class
public File returnData(){
SaveImage(.../*the parameters*/);
Log.e("Exception", "" + directory);
return directory;
}
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);
}
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();
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!