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.
Related
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 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
How can I save multiple lines into One Text File?
I want to print "New Line" in the same Text File every time the code is executed.
try {
FileWriter fw = new FileWriter("Test.txt");
PrintWriter pw = new PrintWriter(fw);
pw.println("New Line");
pw.close();
}
catch (IOException e)
{
System.out.println("Error!");
}
I'm able to create a new file but can't create a new line every time the code is executed.
Pass true as a second argument to FileWriter to turn on "append" mode.
FileWriter fw = new FileWriter("filename.txt", true);
That will make your file to open in the append mode, which means, your result will be appended to the end of the file each time you'll write to the file. You can also write '\n' after each content writing so that it will inserts a new line there.
You are creating a new line every time it is run, the problem is that you are truncating the file when you open it. I suggest you append to the file each time.
try (FileWriter fw = new FileWriter("Test.txt", true); // true for append
PrintWriter pw = new PrintWriter(fw)) {
pw.println("New Line");
} // try-with-resource closes everything.
Note: openning and closing a file for each line is expensive, If you do this a lot I suggest leaving the file open and flushing the output each time.
You are doing this:
FileWriter fw = new FileWriter("Test.txt");
which is overwriting the file every time you execute that line...
BUT you need instead to append the data to the file
FileWriter fw = new FileWriter("Test.txt", true);
take a look at the constructor in the doc
You need to open the file in append mode. You can do that as follows:
FileWriter fw = new FileWriter("Test.txt", true);
Here is the documentation for the same.
Hello so today ive been working with txt docs and writing files so i currently have this code
try {
File file = new File("./Data/Email/Subscribed.txt");
if (!file.exists()) {
file.createNewFile();
}
FileWriter fw = new FileWriter(file.getAbsoluteFile());
BufferedWriter bw = new BufferedWriter(fw);
bw.write(player.playerEmail + ",");
bw.close();
} catch (IOException e) {
e.printStackTrace();
}
So my question is how do i make it so every time something is written to the file it writes to the next line down
Wrap the BufferedWriter in a PrintWriter and replace the write() calls with println().
Now, every call inserts text on a new line.
I've been working on a small project in Java. The program writes to a log file from different methods . But each time a method is used , the content of the file gets deleted and all what's written in it is the result of the last method.
here's a code snippet of the program :
// dir , log_file , exp_date and amount are declared in the code removed
public static void WriteHeader() throws IOException
{
FileWriter fileWriter = new FileWriter(dir+"/"+log_file);
BufferedWriter bufferedWriter = new BufferedWriter(fileWriter);
Console console = System.console();
exp_date = console.readLine("Enter a string here: ");
bufferedWriter.write(exp_date);
bufferedWriter.close();
}
public static void WriteNewLine() throws IOException
{
FileWriter fileWriter = new FileWriter(dir+"/"+log_file);
BufferedWriter bufferedWriter2 = new BufferedWriter(fileWriter);
Console console = System.console();
amount = console.readLine("Enter another string here :");
bufferedWriter2.newLine();
bufferedWriter2.write(amount);
bufferedWriter2.close();
}
You need to create the writer in append mode http://docs.oracle.com/javase/6/docs/api/java/io/FileWriter.html#FileWriter(java.io.File, boolean)
You need to open file in append mode otherwise once you close the file and reopen it to write, it would erase previous data. http://docs.oracle.com/javase/6/docs/api/java/io/FileWriter.html#FileWriter(java.lang.String, boolean)
FileWriter fileWriter = new FileWriter(dir+"/"+log_file, true);
FileWriter fw = new FileWriter(file, true);
I am pretty sure FileWriter has an overloaded constructor for appending to a file instead of overwriting a file
I would also check if the file exists first.
file.exists();