gpt4 book ai didi

java - 创建文件并写入(空指针)

转载 作者:行者123 更新时间:2023-12-01 21:11:14 25 4
gpt4 key购买 nike

我想创建一个从文件中读取的方法,然后创建一个文件,然后该文件将写入所读取内容的某个子集,但我在 output.write(line)< 处不断收到空指针异常 我不知道为什么?

public void readCreateThenWriteTo(String file, String startRowCount, String totalRowCount) {
BufferedReader br = null;
File newFile = null;
BufferedWriter output = null;
StringBuilder sb = null;
int startRowCountInt = Integer.parseInt(startRowCount);
int totalRowCountInt = Integer.parseInt(totalRowCount);

try {
br = new BufferedReader(new FileReader(file));
sb = new StringBuilder();
newFile = new File("hiya.txt");
output = new BufferedWriter(new FileWriter(newFile));
String line = "";
int counter = 0;

while (line != null) {
line = br.readLine();

if (startRowCountInt <= counter && counter <= totalRowCountInt) {
System.out.println(line);
output.write(line);
}
counter++;
}

} catch (IOException e) {
// TODO Auto-generated catch block
LOGGER.info("File was not found.");
e.printStackTrace();
} finally {
// Should update to Java 7 in order to use try with resources and then this whole finally block can be removed.
try {
if ( br != null ) {
br.close();
}
if ( output != null ) {
output.close();
}
} catch (IOException e) {
// TODO Auto-generated catch block
LOGGER.info("Couldn't close BufferReader.");
e.printStackTrace();
}
}
}

最佳答案

在进入循环之前,您需要检查readLine()的结果:

while ((line = br.readLine()) != null) {
if (startRowCountInt <= counter && counter <= totalRowCountInt) {
System.out.println(line);
output.write(line);
}
counter++;
}

关于java - 创建文件并写入(空指针),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41113234/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com