如何初始化一个输入流

How to initialize an 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();
}

上面的代码是我正在使用的部分,如果您需要我post 其他带有 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 内。
  • ScannerAutoCloseable,因此您可以使用 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();  
}