I am using below code to write data in a file.
public static void writeDataToFile(final String fileName, final String fileContents) {
try {
File file = new File(Environment.getExternalStorageDirectory() + fileName);
if (!file.exists()) {
file.createNewFile();
}
FileWriter writer = new FileWriter(file, true);
writer.append(fileContents);
writer.flush();
writer.close();
} catch (IOException e) {
LogUtility.logInfo(TAG, e.getMessage());
}
}
Here FileWriter Constructor takes boolean that means it concatenates data to file every time to the last data. What I am trying to get is to have a file that has logs of my activities I am performing. And I am achieving via above mentioned code. but the problem is it is always concatenating logs to the last of data every time. What I want is to write new log on starting ever time.By this I will not have search file to the bottom for last log. It will be on start evyer time. Any help
You can set the append flag to false in the FileWriter constructor. Then, use the write() function instead of the append() function
FileWriter writer = new FileWriter(file, false);
writer.write(fileContents);
Why don't you remove the file if it exists:
if (!file.exists()) {
file.createNewFile();
} else {
file.delete()
file.createNewFile();
}
If file does not exist, you have written code to create a new file.
Likewise, if file exists, you can delete the file, and create new one
Before deleting old file, you can copy contents into a String, and add them to content that is to be written in file before writing into file.
StringBuilder contentToWrite = new StringBuilder();
contentToWrite.append(newContent);
if (!file.exists()) {
file.createNewFile();
} else {
FileReader fileReader = new FileReader(file);
BufferedReader bufferedReader = new BufferedReader(fileReader);
String line = bufferedReader.readLine();
StringBuilder sb = new StringBuilder();
while (line != null) {
sb.append(line).append("\n");
line = bufferedReader.readLine();
}
contentToWrite.append("\n\n" + sb);
file.delete();
file.createNewFile();
}
FileWriter writer = new FileWriter(file, true);
writer.append(contentToWrite);
writer.flush();
writer.close();
PS: Don't forget to close FileReader and BufferedReader in a finally statement.
Related
I have an AWS lambda program written in Java that is supposed to create a bunch of txt files then write URLs to them and move them to a bucket. It appears to be creating the .txt files in the /tmp/ folder of the lambda but not writing anything to them, because I keep getting FL2: null. The bucket gets .txt files with the right names but they're empty.
The FileNames are all of the format "/tmp/[name].txt". The map has txt filenames followed by a list of URLs. The buffered reader was simply my own code to see if it could read the .txts that were created.
for (Map.Entry<String, ArrayList<String>> entry: files.entrySet()) {
String fileName = entry.getKey();
ArrayList<String> list = entry.getValue();
File file = new File(fileName);
FileWriter writer = null;
BufferedWriter bw = null;
BufferedReader br = null;
try {
if (!file.exists()){
log.info("It doesn't exist as a temp.");
if( !file.createNewFile()){
log.error(fileName+" not created. Skipping");
continue;
}
}
writer = new FileWriter(file, StandardCharsets.UTF_8);
bw = new BufferedWriter(writer);
for (int i=0; i< list.size(); i++) {
String url = list.get(i);
log.info("Inserting " + url + " into file " + fileName);
if (i !=0){
bw.write("\n");
}
bw.write(url);
}
br = new BufferedReader(new FileReader(file, StandardCharsets.UTF_8));
log.info("FL2: "+br.readLine());
String key = fileName.substring(5);
amazonS3.putObject("[bucketname]", key, file);
} catch (Exception e) {
e.printStackTrace();
}
finally{
try {
if (writer != null) {
writer.close();
}
if (bw != null) {
bw.close();
}
if (br != null) {
br.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
log.info("End of the sitemap generator");
}
I tried the above code, and I tried printWriter turning into a bufferedWriter.
Your code is writing to the text file and later reading from the same text file. But ... your code doesn't close the writer until the finally section of code so the read happens before the writer closes and consequently the written data, which is buffered, has not been flushed to disk.
The fix is to close the buffered writer before reading from the same file.
Also, you can reduce the amount of state in your program as follows, while also reducing the number of closes you have to do:
BufferedWriter bw = new BufferedWriter(new FileWriter(file, ...));
You might also consider using try-with-resources to auto flush/close your files.
I am trying to add a new line to an existing text file, which works but sometimes adds a blank line in between the old data and the new data
So I have a file with the data:
mouse
keyboard
And when adding, it adds it like this:
mouse
keyboard
printer
but I don't want an empty line in between the old and new text.
This is the code I have used:
String filename= "Stock.txt"
FileWriter fw = new FileWriter(filename,true);
fw.write(System.lineSeparator() + data);
fw.close();
Buffer reader and Buffer writer are the preferred classes to use when reading and writing too and from files.
You can achieve this a few ways.
Example 1 - Using File, FileWriter and BufferWriter classes with manual close :
File file = new File("Stock.txt");
FileWriter fr = new FileWriter(file, true);
BufferedWriter br = new BufferedWriter(fr);
br.write(data + "\n");
br.close();
fr.close();
Example 2 - Using File, FileWriter and BufferWriter classes with try-with-resource, which will auto-close the resource when processing has ceased :
File file = new File("Stock.txt");
try (FileWriter fileWriter = new FileWriter(file, true);
BufferedWriter bufferedWriter = new BufferedWriter(fileWriter)) {
bufferedWriter.write(data + "\n");
} catch (FileNotFoundException e) {
System.out.println("Unable to open file, file not found.");
} catch (IOException e) {
System.out.println("Unable to write to file." + file.getName());
}
See: https://stackabuse.com/reading-and-writing-files-in-java/ for some really useful info on reading and writing files!
See: https://docs.oracle.com/javase/tutorial/essential/exceptions/tryResourceClose.html for info on try-with-resource.
I need your help with the below code , I am not able to append the text (Hi in my example). the file is being created and I am having inside of it only 1 Hi, however I am looping inside of it ( when I run the cmd I can see it is looping and system printing several hi ) but why i am having in the file 1 hi ?
I made sure that this is true
fw = new FileWriter(file.getAbsoluteFile(), true);
try
{
LineNumberReader rdr = new LineNumberReader(new FileReader(directory+"/Ant_log.log"));
String timeStamp = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss").format(Calendar.getInstance().getTime());
BufferedWriter bw = null;
FileWriter fw = null;
File file = new File(directory+"/Log-Missing-scripts.txt");
String line1 ="";
while((line1 = rdr.readLine())!= null)
{
// if file doesnt exists, then create it
if (!file.exists()) {
file.createNewFile();
}
// true = append file
fw = new FileWriter(file.getAbsoluteFile(), true);
bw = new BufferedWriter(fw);
System.out.println(rdr.getLineNumber());
if (rdr.getLineNumber()== 3)
{
System.out.println("Hi");
bw.write("Hi");
break;
}
}
bw.close();
writer.close();
}
catch(Exception e)
{
System.out.println("ERROR : In Log File");
}
}
move your file and *Writer creation code to before the loop, otherwise you are creating new Writers each iteration. Only the last created Writer is being closed and flushed
I want add few strings to a text file in a particular location.
I have used BufferedReader to read the text file. Then I added the string at the particular position and wrote the modified text to a new temp file using BufferedWriter.
Then I deleted the old file and renamed the temp file to old file name.
This works sometimes and does not work sometimes. The delete() function sometimes does not delete the file. I have closed all the BufferedWriter's, but the problem still occurs sometimes.
Code:
public boolean cart(String uname, String item) throws IOException {
File file = new File("C:\\$$$$.tmp");
if (!file.exists()) {
file.createNewFile();
}
FileWriter fw = new FileWriter(file.getAbsoluteFile(), true);
BufferedWriter bw = new BufferedWriter(fw);
File fileop = new File("C:\\value.text");
FileReader fr = new FileReader(fileop.getAbsoluteFile());
BufferedReader br = new BufferedReader(fr);
String line;
while((line = br.readLine()) != null) {
String val[] = line.split(",");
if (val[0].equals(uname)) {
String linenew = line + item + "&";
bw.append(linenew);
bw.newLine();
bw.flush();
} else {
bw.append(line);
bw.newLine();
bw.flush();
}
}
br.close();
bw.close();
fileop.delete();
file.renameTo(fileop);
return true;
}
I found the answer by myself after spending one full day of searching..
Answer is:
It is enough to close the bufferedReader but also the fileReader..
fr.close(); should be inserted after br.close();
This is my code to delete a line of text from a text file. I have an add function which appends a line of text to the text file. When I delete every line of text from the text file and add back some lines of text using my add function, the delete() always fails. I checked that the file exists, and have closed everything I could and thus not sure why the delete would fail. How do I proceed to debug this problem without knowing why the delete fails?
{
int currLineNum = 1;
File temp = new File("temp.txt");
BufferedReader reader = new BufferedReader(new FileReader(inputFile));
FileWriter fileWriter = new FileWriter(temp, true);
BufferedWriter buffer = new BufferedWriter(fileWriter);
PrintWriter printWriter = new PrintWriter(buffer);
String currentLine;
// .. loop omitted ..
reader.close();
printWriter.close();
buffer.close();
fileWriter.close();
if(inputFile.delete()) //code fails here
System.out.println("DELETED");
else
System.out.println("FAILED");
if(temp.renameTo(inputFile))
System.out.println("DONE");
else
System.out.println("NOT DONE");
}