我在这个程序中遇到了一个例外。我试图做一些改变,但它仍然无法正常工作。我正在尝试将数据从 demo.txt 写入 demo1.txt,但它给出了NullPointerException
. 我在这里做错了什么?
import java.io.*;
class CopyFile{
public static void main(String[] args){
String str = null ;
try {
File f = new File("/home/newlabuser/workspace/CopyFileDemo/src/demo.txt");
if(f.exists())
{
if(f.canRead())
{
FileInputStream fin = new FileInputStream(f);
BufferedInputStream bin = new BufferedInputStream(fin);
DataInputStream din = new DataInputStream(bin);
while((str=din.readLine())!=null)
System.out.println(str);
writeTextFile("/home/newlabuser/workspace/CopyFileDemo/src/demo1.txt",str);
din.close();
}
}
}
catch (Exception e) {
e.printStackTrace();
}
}
public static void writeTextFile(String fileName, String s) {
FileWriter output;
try {
output = new FileWriter("/home/newlabuser/workspace/CopyFileDemo/src/demo1.txt");
BufferedWriter writer = new BufferedWriter(output);
writer.write(s);
writer.close();
}
catch (IOException e) {
e.printStackTrace();
}
}
}
java.lang.NullPointerException
在 java.io.Writer.write(Writer.java:140)
在 CopyFile.writeTextFile(CopyFile.java:37)
在 CopyFile.main(CopyFile.java:21)