I'm quite new in OOP and Java programming, so please, forgive me. I wrote a small class in which I try to write a String in a file using the BufferedReader class. Everything works just fine, but the file is "empty", I mean that I can't see anything inside.
But for sure, data are stored, because when I close Eclipse and re open it again and run the driver class to make my tests, data are restored from the file. By the way I use a "try with resources" mechanism so my file is "closed" automatically.
Does someone already meet this problem? My Eclipse version is "2018-12"
Below, you have the small class with a "writeToFile" method in which I use the BufferedReader class.
package parlons.code.tipcalulator.utilities;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
public class FileManagement {
private File tipFile;
public FileManagement(String tipsFileName) {
this.tipFile = new File("/"+tipsFileName);
}
public String readFromFile() {
String tip = null;
try(BufferedReader bufferedReader = new BufferedReader(new FileReader(this.tipFile))) {
tip = bufferedReader.readLine();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return tip;
}
public void writeToFile(String decimal) {
try(BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter(tipFile,true))){
bufferedWriter.write(decimal);
} catch (IOException e) {
e.printStackTrace();
}
}
}
Below, you'll find the Driver class for testing purposes.
package parlons.code.tipcalulator.utilities;
public class UtilitiesTestDriver {
public static void main(String[] args) {
String decimal = "108";
FileManagement fileManagement = new FileManagement("tipFile.txt");
fileManagement.writeToFile(decimal);
System.out.println(fileManagement.readFromFile());
}
}
As per Makoto's comment above, everything works fine if you change to e.g.:
this.tipFile = new File("./"+tipsFileName);
This would create the tipFile.txt file (containing 108) in the root directory of your project (as opposed to the root of the filesystem - where you would probably not have write permission.)