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
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 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.
i have a Runnable thread that refresh every 5 seconds.
This thread want to write on file named with time and date.
i check if file exists, i want to append the new update on the existed file and, when minute change, generate a new file and do the same on it every 5 seconds.
The application is based on JFrame Application Form
Runnable helloRunnable = new Runnable(){
#override
public void run(){
try{
String FileName = Calendar.getInstance().get(Calendar.HOUR_OF_DAY) + Calendar.getInstance().get(Calendar.MINUTE) + ".txt";
File f = new File(FileName);
FileWriter filewriter = new FileWriter(FileName);
BufferedWriter bufferedWriter = new BufferedWriter(filewriter);
FileWriter filewriter2 = new FileWriter(f, true);
BufferedWriter = bufferedWriter2 = new BufferedWriter(filewriter2);
if (f.isFile() && !f.isDirectory()){
bufferedWriter2.write("Hello"); //this part doesn't append "Hello" in file (as i want) but overwrite the existing file
bufferedWriter2.close();
}else{
bufferedWriter.write("Hello"); //this part must overwrite the existing file so i think this work
bufferedWriter.close();
}
} catch (IOExcception ex){
Logger.getLogger(Gestionale.class.getName()).log(Level.SEVERE,nell,ex);
}
}
};
ScheduledExecutorService executor = Executors.newScheduledThreadPool(1);
SchedulateFuture<?> ez = executor.scheduleFixedRate(helloRunnable,0,5,TimeUnit.SECONDS);
You are always instantiating a FileWriter that overwrites an existing file.
FileWriter filewriter = new FileWriter(FileName);
After this line the file will always be empty.
You have to move the creation of the FileWriter objects into the if statement.
I have this method that takes one String and writes it to a file. I set the PrintWriter to true because I want to save all the data that is written to it.
I want to have headings on this file. How can I write the headlines to the file and only do it one time?
My method looks like this:
public static void writeToFile(String text) {
try {
File f = new File("test.txt");
FileWriter writer = new FileWriter("test", true);
writer.write(text);
writer.close();
} catch (IOException ex) {
System.out.println(ex.getMessage());
}
}
It's not clear whether your file has multiple heading or not. Assuming your file has only one heading we can do this as follow -
1. Since your file contain heading only one time, you can check whether the file is accessing for the first time -
File f = new File(//your file name);
if(f.exists() && !f.isDirectory()) {
//write heading
}
2. If the file is first time accessed then you can add a header -
String heading = "Some heading";
The full code looks like -
public static void writeToFile(String text) {
String heading = "Some heading";
try {
File f = new File("test.txt");
FileWriter writer = new FileWriter(f, true);
if(f.exists() && !f.isDirectory()) {
writer.write(heading);
}
writer.write(text);
} catch (IOException ex) {
System.out.println(ex.getMessage());
}finally{
writer.close();
}
}
You can use BufferWriter to write a sentence and take a look at a better way to handle the file.
try {
String content = "This is the content to write into file";
File f = new File("test.txt");
// if file doesnt exists, then create it
if (!file.exists()) {
file.createNewFile();
}
FileWriter fw = new FileWriter(file.getAbsoluteFile());
BufferedWriter bw = new BufferedWriter(fw);
bw.write(content);
bw.close();
System.out.println("Done");
} catch (IOException e) {
e.printStackTrace();
}finally{
writer.close();
}
}
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();