文件编写器和文件 Reader 错误
File Writer and File Reader error
我有这段代码可以从文本文件中读取然后修改它。然后将修改后的内容写到另一个文本文件中。
我在 out.write(read);
处收到空指针异常而且,并非所有行都被写入,请有人帮助我。谢谢
import java.util.*;
import java.io.*;
public class File
{
BufferedReader in;
BufferedWriter out;
String read;
public File()
{
try {
in = new BufferedReader(new FileReader("myFile.txt"));
Scanner scan = new Scanner(in);
out = new BufferedWriter(new FileWriter("output.txt"));
while (scan.hasNext()) {
read = in.readLine();
//Write codes to modify file here
//___codes not written yet______//
out.write(read);
scan.next();
System.out.println("file output: " + read);
}
out.close();
in.close();
} catch (IOException e) {
System.out.println("There was a problem:" + e);
}
}
public static void main(String[] args)
{
File File = new File();
}
}
尝试
while((read = in.readLine()) != null)
而不是
while (scan.hasNext())
需要更改:while((read = in.readLine()) != null).
我有这段代码可以从文本文件中读取然后修改它。然后将修改后的内容写到另一个文本文件中。
我在 out.write(read);
处收到空指针异常而且,并非所有行都被写入,请有人帮助我。谢谢
import java.util.*;
import java.io.*;
public class File
{
BufferedReader in;
BufferedWriter out;
String read;
public File()
{
try {
in = new BufferedReader(new FileReader("myFile.txt"));
Scanner scan = new Scanner(in);
out = new BufferedWriter(new FileWriter("output.txt"));
while (scan.hasNext()) {
read = in.readLine();
//Write codes to modify file here
//___codes not written yet______//
out.write(read);
scan.next();
System.out.println("file output: " + read);
}
out.close();
in.close();
} catch (IOException e) {
System.out.println("There was a problem:" + e);
}
}
public static void main(String[] args)
{
File File = new File();
}
}
尝试
while((read = in.readLine()) != null)
而不是
while (scan.hasNext())
需要更改:while((read = in.readLine()) != null).