This is my code :
FileWriter fw = new FileWriter(log,true);
BufferedWriter bw = new BufferedWriter(fw);
StringWriter sw = new StringWriter();
PrintWriter pw = new PrintWriter(sw);
fw.close();
bw.close();
sw.close();
pw.close();
I want to change it to something like this :
BufferedWriter bw = new BufferedWriter(new FileWriter(log,true));
PrintWriter pw = new PrintWriter(new StringWriter());
bw.close();
pw.close();
Will this be correct, or will the missing close() calls cause problems?
To be sure the close is not forgotten you could use the try-with-resource statement
try (BufferedWriter bw = new BufferedWriter(new FileWriter(log, true));
PrintWriter pw = new PrintWriter(new StringWriter())) {
// do your processing here
} catch (IOException ex) {
// do your exception handling
}
The compiler will add for your the appropriate code for the close().
When you close a BufferedWriter Object which takes a FileWriter Object in its constructor, then implicitly the FileWriter Object is also closed.
So to answer your question, both ways are fine and the same and it don't make any problem
Previous Answer
Best practice
Since Java 7 you can let java automatically close the resources for you. Take a look at the try with resources.
try (BufferedReader br = new BufferedReader(new FileReader(path))) {
return br.readLine();
}
Related
My current problem is that I would like to write to and read from a file, however, I keep trying to throw exceptions and instantiating my variables only to keep getting errors about how the variables I've declared 'could not have been instantiated.' I'm unsure how to fix this problem.
I've tried using PrintWriter and FileWriter, briefly tried BufferedWriter and other solutions to no avail. I do not know what else I can try.
{
public SettingsHandler()
{
File configFile=new File(this.getClass().getResource("file").getFile());
try{
file = new Scanner(configFile);
}catch (FileNotFoundException e){
System.out.println("Config.ini not found");
}
}
public void saveSetting(String setting, String value)
{
FileWriter fw;
try{
fw = new FileWriter("myfile.txt", true);
}catch (IOException e){
}
BufferedWriter bw = new BufferedWriter(fw);
PrintWriter out = new PrintWriter(bw);
}
}
Every time I try creating the PrintWriter, it gives me an error for the bw parameter: "variable fw might not have been initialized."
Does anyone know how to solve this issue?
"variable fw might not have been initialized."
You need to see more closely your code. The IDE saw this scenario.
FileWriter fw;
try{
fw = new FileWriter("myfile.txt", true); ==> An exception can happen
}catch (IOException e){
nothing to do...
}
BufferedWriter bw = new BufferedWriter(fw); ==> fw is not initialized..
PrintWriter out = new PrintWriter(bw);
Workarounds for this...
Scenario 1
FileWriter fw = null; // Very pointles...
try{
fw = new FileWriter("myfile.txt", true);
}catch (IOException e){
}
BufferedWriter bw = new BufferedWriter(fw);
PrintWriter out = new PrintWriter(bw);
Scenario 2 Move to the try catch
try{
FileWriter fw = new FileWriter("myfile.txt", true); //Well a little better
BufferedWriter bw = new BufferedWriter(fw);
PrintWriter out = new PrintWriter(bw);
}catch (IOException e){
}
And so on...
The error "variable fw might not have been initialized" will get resolved by simply initializing your variable fw to null!
FileWriter fw = null; is correct.
--Thanks for asking.
I have a server that writes to a logfile, but I do not want to append lines. I have set the flag to false, but still it seems to be appending. How can I make it REPLACE the first line everytime so my file contains one updated line everytime ?
fos = new FileOutputStream(new File(filename), false);
PrintWriter bw = new PrintWriter(new OutputStreamWriter(fos));
..
..
while(true){
line = getRandomLine();
bw.println(line);
bw.flush();
}
..
..
If I understand You correctly, you want this:
File file = new File(filename);
while (true) {
pw = new PrintWriter(file);
line = getRandomLine();
pw.println(line);
pw.flush();
pw.close();
}
I want to open a file, write it in a loop (append everything to the previous lines) and then close it. I had already implmented everything in a single method inside the loop and I had a problem similar to this question. So, I'm trying to implement it according to the suggestion that writing and opening must be done in different steps. My code now is like the following:
PrintWriter out= createAndOpenFile(fileName);
for (int i = 0 ; i< test.size(); i++){
writeToFile(mystring, out);
}
out.close();
And the implementation of the above methods are like the following:
private PrintWriter createAndOpenFile(String fileName) {
try (FileWriter fw = new FileWriter(fileName);
BufferedWriter bw = new BufferedWriter(fw);
PrintWriter out = new PrintWriter(bw)) {
return out;
} catch (IOException e) {
e.printStackTrace();
return null;
}
}
private void writeToFile(String features, PrintWriter out) {
out.println(features);
out.flush();
}
Can anyone tell me what is wrong with my code?
Update: With "not working" I meant that the file is empty at the end, though created.
As #khelwood says, out is closed at the return statement. That's expected.
If you do the writeToFile's inside the try, it works (the file will not be empty):
try (FileWriter fw = new FileWriter("c:/temp/tt.txt");
BufferedWriter bw = new BufferedWriter(fw);
PrintWriter out = new PrintWriter(bw)) {
writeToFile(mystring, out);
out.close();
} catch (IOException e) {
e.printStackTrace();
}
I have tried using writer.newLine() however it says method not found. Does anyone know how I can write a new line after each iteration?
public static void keepLetters() throws IOException {
BufferedReader sourceReader = new BufferedReader(new FileReader("input.txt"));
for (String line = sourceReader.readLine(); line != null; line = sourceReader.readLine()) {
String updatedLine = line.replaceAll("[^A-Za-z]", "");
System.out.println(updatedLine);
try (Writer writer = new BufferedWriter(new OutputStreamWriter(
new FileOutputStream("output.txt"), "UTF-8"))) {
writer.write(updatedLine);
}
}
}
I wrote writer.nextLine() after writer.write(updatedLine);
Thank you
The correct method is newLine(), but you need to call it on a BufferedWriter, not a Writer.
Like so:
try (BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(
new FileOutputStream("output.txt", true), "UTF-8"))) {
writer.write(updatedLine);
writer.newLine();
}
Note this part try (BufferedWriter writer
Update for comment
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream("output.txt"), "UTF-8"));
for (int i = 0; i < linesToWrite; i++){
writer.write(updatedLine);
writer.newLine();
}
writer.close();
You can simple do
writer.write(updatedLine + "\n");
which will ensure a newline is written after every updatedLine.
EDIT:
The writer is being reinitiated to the same file output every iteration of the loop. It should be initialised once before the loop and closed later on to resolve your issue.
I followed this link and I came up with below code
try {
File file = new File(
"C:/dataset.txt");
// if file doesnt exists, then create it
if (!file.exists()) {
file.createNewFile();
}
FileWriter fw = new FileWriter(file.getAbsoluteFile(), true);
BufferedWriter bw = new BufferedWriter(fw);
List<Integer> data = generateData(args);
// one per line
for (final int i : data) {
bw.write(i);
bw.newLine(); // Here it throws NullPointerException
}
bw.close();
} catch (IOException e) {
System.out.print(e);
}
NOTE: Even if I move bw.newLine(); before for loop, it throws NullPointerException.
Image
Am I missing anything ?
To add a line seperator you could use this.
//to add a new line after each value added to File
String newLine = System.getProperty("line.separator");
and then call it like so:
bw.write(newLine);
EDIT:
since you cant use a System.getProperty with a BufferWriter I would suggest the code below:
private FileOutputStream fOut;
private OutputStreamWriter writer;
fOut = openFileOutput(FILE_NAME, Context.MODE_PRIVATE);
writer = new OutputStreamWriter(fOut);
writer.append(.... whatever you wish to append ...);
writer.append(separator);
writer.flush();
fOut.close();
Hope that helps!