我当前的问题是,我想写入和读取文件,但是,我一直尝试抛出异常并实例化我的变量,只是为了不断收到有关我声明的变量“不可能”的错误实例化。我不确定如何解决这个问题。
我尝试过使用 PrintWriter 和 FileWriter,短暂尝试过 BufferedWriter 和其他解决方案,但均无济于事。我不知道我还能尝试什么。
{
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);
}
}
每次我尝试创建 PrintWriter 时,都会出现 bw 参数错误:“变量 fw 可能尚未初始化。”
有人知道如何解决这个问题吗?
最佳答案
"variable fw might not have been initialized."
您需要更仔细地查看您的代码。 IDE 看到了这种情况。
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);
此问题的解决方法...
场景 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);
场景 2 转到 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){
}
等等...
关于java - 如何写入和读取同一个文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56478359/