I have a simple class file called File.java with 3 functions in it: createFile, writeContent and the obligatory main function as a driver:
import java.io.*;
class CreateFile {
public static boolean createFile(File file, String fileName) throws IOException {
if (file.createNewFile()){
System.out.println(fileName + ": File created successfully!");
return false;
} else {
System.out.println(fileName + ": File already existing!");
return true;
}
}
public static void writeContent(String fileName, String fileContent, boolean append) throws IOException {
if (append = false) {
BufferedWriter writer = new BufferedWriter(new FileWriter(fileName, false));
} else {
BufferedWriter writer = new BufferedWriter(new FileWriter(fileName, true));
}
writer.write(fileContent);
writer.close();
}
public static void main(String[] args) throws IOException {
String fileName = "file.txt";
File file = new File(fileName);
boolean append = createFile(file, fileName);
String fileContent = "Hello, this is a test";
writeContent(fileName, fileContent, append);
}
}
Run Code Online (Sandbox Code Playgroud)
The trouble is with the function writeContent, which is called in the last line. There is a basic if condition, checking whether the writing process needs to append to the file, or not (I know this is not necessary, but I am still testing, so bear with me).
I get an error saying the compiler can't find the symbol writer, meaning that the BufferedWriter writer is created before checking the if condition. This is precisely what I don't get: Why isn't the if condition executed beforehand?
If I include the write commands in the if and the else statement it works beautifully, but that causes code redundancy which is what I am trying to circumvent:
public static void writeContent(String fileName, String fileContent, boolean append) throws IOException {
if (append = false) {
BufferedWriter writer = new BufferedWriter(new FileWriter(fileName, false));
writer.write(fileContent);
writer.close();
} else {
BufferedWriter writer = new BufferedWriter(new FileWriter(fileName, true));
writer.write(fileContent);
writer.close();
}
}
Run Code Online (Sandbox Code Playgroud)
I am sure I am simply obtuse to something fundamental & simple - would you mind giving me a hint here?
Change this:
if (append = false) {
BufferedWriter writer = new BufferedWriter(new FileWriter(fileName, false));
} else {
BufferedWriter writer = new BufferedWriter(new FileWriter(fileName, true));
}
Run Code Online (Sandbox Code Playgroud)
Change to:
BufferedWriter writer;
if (append == false) {
writer = new BufferedWriter(new FileWriter(fileName, false));
} else {
writer = new BufferedWriter(new FileWriter(fileName, true));
}
Run Code Online (Sandbox Code Playgroud)
If you create variable inside braces {} it's scope is limited to them.
So, you should create writer
outside if
, because you use it later.
归档时间: |
|
查看次数: |
81 次 |
最近记录: |