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();
Related
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 running another jar with this code:
(I am updating a gui in some parts , so dont feel confused.)I get an IO Exception (Stream Closed) here:
if((line = readr.readLine()) != null){
Thats the full code:
if(!data.serverStarted()){
try{
data.updateConsole("Starting server!");
String fileDir = data.dir + File.separator + "craftbukkit.jar";
Process proc = Runtime.getRuntime().exec("java -Xmx2048M -jar "+"craftbukkit.jar"+" -o true --nojline");
data.setOutputStream(proc.getOutputStream());
InputStream is = proc.getErrorStream();
}catch(IOException ex){
ex.printStackTrace();
}
BufferedReader readr = new BufferedReader(new InputStreamReader(is));
data.setServerStarted(true);
String line;
while(data.serverStarted()){
try {
if((line = readr.readLine()) != null){
data.updateConsole(line);
}
} catch (IOException e) {
e.printStackTrace();
}finally{
try {
readr.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}else{
data.updateConsole("You have already started your server!");
}
You have a while loop that closes readr on every pass. The next time it gets to the try block, readr is closed. Perhaps you intended to put the try/catch block around the while loop?
You are closing the reader inside the loop that reads from it. You need to close it outside of the loop:
try {
String line;
while (data.serverStarted() && ((line = readr.readLine()) != null)) {
try {
data.updateConsole(line);
} catch (IOException e) {
e.printStackTrace();
}
}
} finally {
try {
readr.close();
} catch (IOException e) {
e.printStackTrace();
}
}
I am surprised that this code even compiles.
You declare the actual InputStream is inside the try/catch at the beginning, but that makes it only visible inside that block. So whatever you give to the BufferedReader a few lines below is something else and most likely not what you think it is.
In addition your while(data.serverStarted()) does not check if the stream is still open, and later you only use a single if check (again with no check if the stream is open), so you'll only read one single line at best.
I have a feeling that you had a bad OutOfCoffeeException while writing this code. ;)
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)
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.
Wrote up a basic file handler for a Java Homework assignment, and when I got the assignment back I had some notes about failing to catch a few instances:
Buffer from file could have been null.
File was not found
File stream wasn't closed
Here is the block of code that is used for opening a file:
/**
* Create a Filestream, Buffer, and a String to store the Buffer.
*/
FileInputStream fin = null;
BufferedReader buffRead = null;
String loadedString = null;
/** Try to open the file from user input */
try
{
fin = new FileInputStream(programPath + fileToParse);
buffRead = new BufferedReader(new InputStreamReader(fin));
loadedString = buffRead.readLine();
fin.close();
}
/** Catch the error if we can't open the file */
catch(IOException e)
{
System.err.println("CRITICAL: Unable to open text file!");
System.err.println("Exiting!");
System.exit(-1);
}
The one comment I had from him was that fin.close(); needed to be in a finally block, which I did not have at all. But I thought that the way I have created the try/catch it would have prevented an issue with the file not opening.
Let me be clear on a few things: This is not for a current assignment (not trying to get someone to do my own work), I have already created my project and have been graded on it. I did not fully understand my Professor's reasoning myself. Finally, I do not have a lot of Java experience, so I was a little confused why my catch wasn't good enough.
Buffer from file could have been null.
The file may be empty. That is, end-of-file is reach upon opening the file. loadedString = buffRead.readLine() would then have returned null.
Perhaps you should have fixed this by adding something like if (loadedString == null) loadedString = "";
File was not found
As explained in the documentation of the constructor of FileInputStream(String) it may throw a FileNotFoundException. You do catch this in your IOException clause (since FileNotFoundException is an IOException), so it's fine, but you could perhaps have done:
} catch (FileNotFoundException fnfe) {
System.err.println("File not fonud!");
} catch (IOException ioex {
System.err.println("Some other error");
}
File stream wasn't closed
You do call fin.close() which in normal circumstances closes the file stream. Perhaps he means that it's not always closed. The readLine could potentially throw an IOException in which case the close() is skipped. That's the reason for having it in a finally clause (which makes sure it gets called no matter what happens in the try-block. (*)
(*) As #mmyers correctly points out, putting the close() in a finally block will actually not be sufficient since you call System.exit(-1) in the catch-block. If that really is the desired behavior, you could set an error flag in the catch-clause, and exit after the finally-clause if this flag is set.
But what if your program threw an exception on the second or third line of your try block?
buffRead = new BufferedReader(new InputStreamReader(fin));
loadedString = buffRead.readLine();
By this point, a filehandle has been opened and assigned to fin. You could trap the exception but the filehandle would remain open.
You'll want to move the fin.close() statement to a finally block:
} finally {
try {
if (fin != null) {
fin.close();
}
} catch (IOException e2) {
}
}
Say buffRead.readLine() throws an exception, will your FileInputStream ever be closed, or will that line be skipped? The purpose of a finally block is that even in exceptional circumastances, the code in the finally block will execute.
There are a lot of other errors which may happen other than opening the file.
In the end you may end up with a fin which is defined or not which you have to protect against null pointer errors, and do not forget that closing the file can throw a new exception.
My advice is to capture this in a separate routine and let the IOExceptions fly out of it :
something like
private String readFile() throws IOException {
String s;
try {
fin = new FileInputStream(programPath + fileToParse);
buffRead = new BufferedReader(new InputStreamReader(fin));
s = buffRead.readLine();
fin.close();
} finally {
if (fin != null {
fin.close()
}
}
return s
}
and then where you need it :
try {
loadedString = readFile();
} catch (IOException e) {
// handle issue gracefully
}