[英]Can not write to java txt file
我當前正在使用blueJ學習Java,並且有一個作業,我必須在其中寫入txt文件,檢查該文件是否存在並讀取該文件。 我下面的代碼可以編譯,但是當我嘗試運行write()方法時,收到以下錯誤java.lang.nullpointerexception;
我不知道我要去哪里錯,在這個階段它開始使我發瘋。
import java.io.*;
public class ReadWrite
{
// instance variables - replace the example below with your own
private String file;
private String text;
/**
* Constructor for objects of class ReadWrite
*/
public ReadWrite(String file, String text)
{
// initialise instance variables
file=this.file;
text=this.text;
}
public void write()
{
try{
FileWriter writer = new FileWriter(file);
writer.write(text);
writer.write('\n');
writer.close();
}
catch(IOException e)
{
System.out.print(e);
}
}
public boolean writeToFile()
{
boolean ok;
try{
FileWriter writer = new FileWriter(file);
{
write();
}
ok=true;
}
catch(IOException e) {
ok=false;
}
return ok;
}
public void read(String fileToRead)
{
try {
BufferedReader reader = new BufferedReader(new FileReader(fileToRead));
String line = reader.readLine();
while(line != null) {
System.out.println(line);
line = reader.readLine();
}
reader.close();
}
catch(FileNotFoundException e) {
}
catch(IOException e) {
}
}
}
您的構造函數正在反向分配值。 此刻你有
public ReadWrite(String file, String text)
{
// initialise instance variables
file=this.file;
text=this.text;
}
這會將傳入變量file
和text
分配給實例變量,這些變量為null。
您需要具備的是:
public ReadWrite(String file, String text)
{
// initialise instance variables
this.file = file;
this.text = text;
}
將來避免這種情況的一種有用方法是使您的參數final
可用-這意味着您無法為其分配任何內容,並且會在編譯器中捕獲到該錯誤。
public ReadWrite(final String file, final String text)
{
// won't compile!
file = this.file;
text = this.text;
}
進一步的改進是使實例變量file
和text
final
,這意味着必須對其進行分配。 這樣,您正在使用編譯器來幫助您捕獲錯誤。
public class ReadWrite
{
private final String file;
private final String text;
public ReadWrite(final String file,
final String text)
{
this.file = file;
this.text = text;
}
// ...
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.