Hi I'm using the below method to write to a file from the Jtextarea and I call this method every 30 second within a Timer but instead to add only new line in file it rewrite the entire lines contained in Jtextarea so then I have duplicate lines. I want to avoid this and update the file just with new lines. Could you help me please.
public void loger() {
FileWriter writer = null;
try {
writer = new FileWriter("MBM_Log_"+date()+".txt" , true);
textArea.write(writer);
} catch (IOException exception) {
System.err.println("log error");
exception.printStackTrace();
} finally {
if (writer != null) {
try {
writer.close();
} catch (IOException exception) {
System.err.println("Error closing writer");
exception.printStackTrace();
}
}
}
}
writer = new FileWriter("MBM_Log_"+Date()+".txt" , true);
The code above uses appending boolean flag in the constructor, make it false and retry:
writer = new FileWriter("MBM_Log_"+Date()+".txt" , false);
To avoid creating a new file each time, initialize your file writer once outside the method and then use it:
FileWriter writer = new FileWriter("MBM_Log_"+date()+".txt" , true);
public void loger() {
try {
textArea.write(writer);
} catch (IOException exception) {
System.err.println("log error");
exception.printStackTrace();
} finally {
if (writer != null) {
try {
writer.close();
} catch (IOException exception) {
System.err.println("Error closing writer");
exception.printStackTrace();
}
}
}
}
Change:
writer = new FileWriter("MBM_Log_"+Date()+".txt" , true);
to:
writer = new FileWriter("MBM_Log_"+Date()+".txt", false);
or just:
writer = new FileWriter("MBM_Log_"+Date()+".txt");
The constructor you're using for FileWriter takes two arguments: a String filename and boolean which says whether to append to the file if it already exists. As you currently have this set to true it is appending the contexts of the text area on to the file instead of replacing the file with one with just the current text.
If you want to keep the existing contents of the file either:
Keep using the append option and only update the file when you close the application.
Read the contents of the file on application start up and write this out to the new file before adding the current contents of the text area.
You definitely need to append to the file (so leave true in the constructor).
What you are doing somewhat wrong is to use a Swing component to store data. Swing components are designed to display data. Imagine what would happen if your manager / supervisor / teacher told you to use another GUI library or convert the whole application to a web server - you would have to abandon JTextArea and would then have nowhere to save log messages.
You should have some collection of log messages, for example a List and then display the messages using this collection. Your log message class can have some function to convert the log message into a String. Then it would be just a question to go through the list every 30 seconds and append the messages whose timestamp is newer than the time of the last save.
I changed my code instead to write to the file from the Jtextarea I write the string (LOG) directly to the file. My method loger() become as below :
public void loger (String texLine){
FileWriter writer = null;
try {
writer = new FileWriter("MBM_Log_"+date()+".txt" , true);
PrintWriter out = new PrintWriter(writer);
out.printf("%s"+"%n", texLine);
out.close();
} catch (IOException exception) {
System.err.println("log error");
exception.printStackTrace();
}
finally {
if (writer != null) {
try {
writer.close();
} catch (IOException exception) {
System.err.println("Error closing writer");
exception.printStackTrace();
}
}
}
}
And then then I write the log to the Jtextarea to be displayed in GUI and calling the method loger() to write to the file e.g:
textArea.append(dateTime()+ " : Alarm sound muted by the Operator from the Menu Bar ");
loger(dateTime()+ " : Alarm sound muted by the Operator from the Menu Bar ");
By this way I have the logs in Jtextarea and in the file. My problem is resolved when I restart the application the file is not erased and the new log is added to the file.
Thanks to all.
Related
I want my program to create a file for the user (just for the first time) and write some information to it (it's not just a line and also can be adjusted anytime later). So I did this:
public void write() {
try {
file = new File("c:\\Users\\Me\\Desktop\\text.txt");
if(!file.exists()) // I found this somewhere on the internet for File class
file.createNewFile(); // not to remove contents. I have no idea if it works
writer = new Formatter(file);
} catch(Exception e) {
e.printStackTrace();
}
writer.format("%s %s ", nameInput.getText(),lastNameInput.getText());
writer.close();
}
It works but there some problems:
When the file gets opened later, as default, the File class removes its contents.
When the information is written to the file and Formatter got closed, next time somewhere else in the program when I use it again to write to the file, the information gets updated and not added to the previous ones. And if I don't close it, it won't write.
first af all, this code here:
if(!file.exists())
file.createNewFile();
it only creates a new file in case it doesn't exists in your path.
To write on your file without overwriting it I recommend you to do this:
FileWriter fileWriter;
public void write() {
try {
file = new File("c:\\Users\\Me\\Desktop\\text.txt");
if(!file.exists())
file.createNewFile();
// use a FileWriter to take the file to write on
fileWriter = new FileWriter(file, true); // true means that you do not overwrite the file
writer = new Formatter(fileWriter); // than you put your FileWriter in the Formatter
} catch(Exception e) {
e.printStackTrace();
}
writer.format("%s %s ", nameInput.getText(),lastNameInput.getText());
writer.close();
}
Hope this was helpfull! :)
As people mentioned above, I had to pass the file through the constructor of FileWriter class. this way my first problem got solved (I mentioned them in the question) and for the second one, I had to reopen the Formatter whenever I wanted to add more.
public void write() {
try {
writer = new Formatter(new FileWriter(file,true);
} catch(Exception e) {
e.printStackTrace();
}
writer.format("%s %s ", nameInput.getText(),lastNameInput.getText());
writer.close(); }
creation and initialization of file should be done once and outside the method.
For some reason my String is written partially by PrintWriter. As a result I am getting partial text in my file. Here's the method:
public void new_file_with_text(String text, String fname) {
File f = null;
try {
f = new File(fname);
f.createNewFile();
System.out.println(text);
PrintWriter out = new PrintWriter(f, "UTF-8");
out.print(text);
} catch (IOException e) {
e.printStackTrace();
}
}
Where I print text to a console, I can see that the data is all there, nothing is lost, but apparently part of text is lost when PrintWriter does its job... I am clueless..
You should always Writer#close your streams before you discard your opened streams. This will free some rather expensive system resources that your JVM must quire when opening a file on the file system. If you do not want to close your stream, you can use Writer#flush. This will make your changes visible on the file system without closing the stream. When closing the stream, all data is flushed implicitly.
Streams always buffer data in order to only write to the file system when there is enough data to be written. The stream flushes its data automatically every now and then when it in some way considers the data worth writing. Writing to the file system is an expensive operation (it costs time and system resources) and should therefore only be done if it really is necessary. Therefore, you need to flush your stream's cache manually, if you desire an immediate write.
In general, make sure that you always close streams since they use quite some system resources. Java has some mechanisms for closing streams on garbage collection but these mechanisms should only be seen as a last resort since streams can live for quite some time before they are actually garbage collected. Therefore, always use try {} finally {} to assure that streams get closed, even on exceptions after the opening of a stream. If you do not pay attention to this, you will end up with an IOException signaling that you have opened too many files.
You want to change your code like this:
public void new_file_with_text(String text, String fname) {
File f = null;
try {
f = new File(fname);
f.createNewFile();
System.out.println(text);
PrintWriter out = new PrintWriter(f, "UTF-8");
try {
out.print(text);
} finally {
out.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
Try to use out.flush(); right after the line out.print(text);
Here is a proper way to write in a file :
public void new_file_with_text(String text, String fname) {
try (FileWriter f = new FileWriter(fname)) {
f.write(text);
f.flush();
} catch (IOException e) {
e.printStackTrace();
}
}
I tested you code. You forgot to close the PrintWriter object i.e out.close
try {
f = new File(fname);
f.createNewFile();
System.out.println(text);
PrintWriter out = new PrintWriter(f, "UTF-8");
out.print(text);
out.close(); // <--------------
} catch (IOException e) {
System.out.println(e);
}
You must always close your streams (which will also flush them), in a finally block, or using the Java 7 try-with-resources facility:
PrintWriter out = null;
try {
...
}
finally {
if (out != null) {
out.close();
}
}
or
try (PrintWriter out = new PrintWriter(...)) {
...
}
If you don't close your streams, not only won't everything be flushed to the file, but at some time, your OS will be out of available file descriptors.
You should close your file:
PrintWriter out = new PrintWriter(f, "UTF-8");
try
{
out.print(text);
}
finally
{
try
{
out.close();
}
catch(Throwable t)
{
t.printStackTrace();
}
}
I am making a save/load feature for the settings in my application. Upon launching the program, it tries to find the file. If it fails, it tries to create a file with default settings (code below)
try (FileWriter fileWriter = new FileWriter(absolutePath))
{
fileWriter.write("theme=light\n");
fileWriter.write("resolution=1280x720\n");
fileWriter.write("printfps=false\n");
System.out.println("Reset settings");
load();
}
catch (FileNotFoundException e)
{
System.out.println("Settings File not found.");
}
catch (IOException e)
{
e.printStackTrace();
}
After it has written this, it goes on to load the file. (calling load() method)
In the load method, the application reads the contents of the file (code below).
try (BufferedReader bufferedReader = new BufferedReader(new FileReader(absolutePath)))
{
String line = bufferedReader.readLine();
System.out.println(line);
while(line != null)
{
if (line.contains("="))
{
String key = line;
String value = line;
while (key.contains("="))
{
key = key.substring(0, key.length() - 1);
}
while (value.contains("="))
{
value = value.substring(1);
}
settings.put(key, value);
}
System.out.println(line);
line = bufferedReader.readLine();
}
System.out.println(settings);
}
However, it returns that the file is empty. After messing with breakpoints, I can confirm that the file is indeed not updated at that point. The rather weird thing is that if I pause the application at a later time, the file seems to contain the text that was written to it, even though the file is not touched later in the program.
This makes me believe that it takes some time for the file to update, thus not updating in time for the load() method. Is this correct, or am I missing something? And is there a workaround?
All help is appreciated :)
You're calling load() before you actually saved the file.
To save the file, call fileWriter.close() or just move the load() call out of the try-with-resource block with the FileWriter:
try (FileWriter fileWriter = new FileWriter(absolutePath))
{
fileWriter.write("theme=light\n");
fileWriter.write("resolution=1280x720\n");
fileWriter.write("printfps=false\n");
}
catch (FileNotFoundException e)
{
System.out.println("Settings File not found.");
}
catch (IOException e)
{
e.printStackTrace();
}
// FileWriter closed now and the file contents saved
System.out.println("Reset settings");
load();
I currently am having problems writing to the text file in my code, the entirety of the program is hit and everything will print out to the console. no errors. But the file is empty. Any suggestions?
public textFiles(String filePath)
{
File file = new File(filePath);
try{
fstream = new FileWriter(filePath,true);
}
catch (Exception e){//Catch exception if any
System.err.println("Error: " + e.getMessage());
}
out = new BufferedWriter(fstream);
System.out.println("try");
addToText("WOOOOHOOO");
System.out.println(file.exists());
}
public void addToText(String Line)
{
try {
out.write(Line);
out.newLine();
} catch (IOException e) {
System.err.println("writing Error");
}
System.out.println("SHOULDA F****** WORKED");
}
You're never closing the stream, and so probably never flushing the stream either - the text essentially gets cached when you print it out, and gets flushed to the file in chunks (usually chunks that are much bigger than what you're writing, hence the lack of output.)
Make sure you close the stream when you're done (fstream.close();), and it should work fine (the stream will automatically flush to clear any output when it's closed).
Try this code to write a .txt file in any drive.
try
{
String ss="html file write in java";
File file= new File("F:\\inputfile\\aa.txt");
FileWriter fwhn= new FileWriter(file);
fwhn.write(ss);
fwhn.flush();
}
catch(Exception ex)
{
}
I am writing to a file using this code.
protected void writeFile(String text) {
DataOutputStream os = null;
FileConnection fconn = null;
try {
fconn = (FileConnection) Connector.open("file:///store/home/user/documents/file.txt", Connector.READ_WRITE);
if (!fconn.exists())
fconn.create();
os = fconn.openDataOutputStream();
os.write(text.getBytes());
} catch (IOException e) {
System.out.println(e.getMessage());
} finally {
try {
if (null != os)
os.close();
if (null != fconn)
fconn.close();
} catch (IOException e) {
System.out.println(e.getMessage());
}
}}
the code is working fine.
My problem is if I write first time "Banglore" and when I read it, I get "Banglore".
But, second time when I write "India" and when I read it, I get, "Indialore".
so, basically its content is not changing according the text , I am giving.
Please tell me how to fix this.
writing in a file doesn't remove the content but it just replaces the content, so writing 'india' over 'Bangalore' will replace the 'Banga' with 'India' and the rest would remain the same. If you want to completely remove old content with newer one, you need to truncate()
the file from where the newer data ends. truncate(text.getBytes().length)