How to write to and read from the same file - java

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.

Related

Writing to a file in loop doesn't work

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();
}

New Line while writing into file

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!

How to close a file in java

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();
}

writing multiple lines to a java file

I'm trying to create an error report in Java, but the file reader writes over the same line
every time I find a new error, so all that displays is the last error. How would I prevent this?
public void errorReport(String error)
{
try {
FileWriter fw = new FileWriter(file);
PrintWriter pw = new PrintWriter(fw);
pw.write(error);
pw.close();
} catch (IOException e)
{
e.printStackTrace();
}
} // end error report
FileWriter fw = new FileWriter(file, true);
The second argument is "append mode." If it is true, then the FileWriter will append lines instead of writing over them.
Documentation

How to free the content of a file?

I want to write in a file, if it exists i would like to free the content and to write from the begining of the file this the code that i use but i dont now how to do that.
try {
File f = new File(testPath + "/logtest.txt");
if (f.exists()) {
f.delete();
BufferedWriter bw = new BufferedWriter(new FileWriter(f, true));
bw.write(text);
bw.newLine();
bw.close();
} else {
BufferedWriter bw = new BufferedWriter(new FileWriter(f, true));
bw.write(text);
bw.newLine();
bw.close();
}
} catch (Exception e) {
}
You have to use
BufferedWriter bw = new BufferedWriter(new FileWriter(f, false));
the second parameter append in the FileWriter constructor you are using is a flag witch controls whether the file sould be truncated before the first write or the data writen should be appended.
see javadoc
The second argument to the FileWriter constructor allows to specify whether you want to append to or overwrite the content:
public FileWriter(File file, boolean append) throws IOException
Constructs a FileWriter object given a File object. If the second
argument is true, then bytes will be written to the end of the file
rather than the beginning.
Parameters:
file - a File object to write to
append - if true, then
bytes will be written to the end of the file rather than the beginning
In your code, you pass true. Simply change it to false:
BufferedWriter bw = new BufferedWriter(new FileWriter(f, false));
EDIT: in case the code you gave in your question is inside a loop, here's how you should change it:
try {
File f = new File(testPath + "/logtest.txt");
if (f.exists()) {
f.delete();
}
BufferedWriter bw = new BufferedWriter(new FileWriter(f, false));
for/while (...) { // your loop here
// extract your text
bw.write(text);
}
bw.close();
f.close();
} catch (Exception e) {
// handle exceptions...
}
Doing this will overwrite whatever was there earlier.
String fileName = "foo.txt";
FileWriter fw = null;
try{
fw = new FileWriter(fileName);
fw.write("haha");
} catch (IOException e) {
System.err.println("Could not write to the file.");
}finally{
if(fw!=null)
try {
fw.close();
} catch (IOException e) {
System.err.println("Could not close the file.");
}
}
If you want to append the data use
fw.append();
Try below code.
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
public class FileClient {
public static void main(String[] args) {
try {
String content = "Hello test";
File file = new File("D:\\filename.txt");
// if file doesnt exists, then create it
if (!file.exists()) {
file.createNewFile();
}
FileWriter fw = new FileWriter(file.getAbsoluteFile());
BufferedWriter bw = new BufferedWriter(fw);
bw.write(content);
bw.close();
System.out.println("Done");
} catch (Exception e) {
e.printStackTrace();
}
}
}
You got your file deleted, because you do a f.delete(); in a loop.
You should do a construction like this:
File f = new File(testPath + "/logtest.txt");
if (f.exists()) {
f.delete();
}
BufferedWriter bw = new BufferedWriter(new FileWriter(f, false));
while (...)
String text = ...;
bw.write(text);
bw.newLine();
}
bw.close();
This way you create/delete the file only once.

Categories