如何解决如何初始化 inputStream
我正在尝试初始化一个 InputStream
,但它不允许我这样做。我已经能够初始化 OutputStream
。
public void readData() {
String fileName = "clinicData.txt";
Scanner inputStream;
System.out.println("The file " + fileName +"\ncontains the following line:\n");
try {
inputStream = new Scanner (new File (fileName));
} catch (FileNotFoundException e) {
System.out.println("Error: opening the file " +fileName);
System.exit(0);
}
while (inputStream.hasNextLine()) {
String line = inputStream.nextLine();
System.out.println (line);
}
inputStream.close();
}
上面的代码是我正在处理的部分,如果您需要我使用 outputStream 发布另一部分,请告诉我。
解决方法
你想这样做:
try (Scanner inputStream = new Scanner(new File(fileName))) {
while (inputStream.hasNextLine()) {
String line = inputStream.nextLine();
System.out.println(line);
}
} catch (FileNotFoundException e) {
System.out.println("Error: opening the file " +fileName);
System.exit(0);
}
-
Scanner inputStream;
在try
块中初始化,但是,不能保证初始化成功,您稍后会尝试在while
循环中访问此类实例,这将是错误。将while
循环移动到内部try
块。 -
Scanner
是AutoCloseable
,因此您可以使用 try-with-resources 而省略inputStream.close()
您可以尝试在 FileInputStream
中获取文件,然后使用 Scanner
读取该文件,如下所示
try
{
FileInputStream fis=new FileInputStream("clinicData.txt");
Scanner sc=new Scanner(fis);
while(sc.hasNextLine())
{
System.out.println(sc.nextLine());
}
sc.close();
}
catch(IOException e)
{
e.printStackTrace();
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。