【问题标题】:How to initialize an inputStream [duplicate]如何初始化 inputStream [重复]
【发布时间】:2021-08-09 12:51:09
【问题描述】:

我正在尝试初始化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 的其他部分,请告诉我。

【问题讨论】:

  • 好吧,你不是在初始化一个InputStream,而是一个Scanner。问题是如何用使用InputStream 的代码替换此代码?还是打算使用Scanner 并且代码不起作用?如果是后者,究竟是什么问题?你有错误吗?错误的结果?
  • 您应该正确命名以避免混淆。扫描器和输入流是不同的东西。你也应该定义“它不允许我”,不要让我们猜测。
  • 您不是在尝试创建InputStream,而是在创建Scanner。你应该发布你得到的错误;不过,您的主要问题似乎是变量范围,因为您在初始化范围之外读取并关闭了扫描仪。
  • 你可以在这里找到答案:stackoverflow.com/questions/28594252/…
  • 程序无法正常工作,因为这是一个错误,我被告知要同时使用 Scanner 和 inputStream

标签: java file inputstream


【解决方案1】:

您可以尝试在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();  
}

【讨论】:

    【解决方案2】:

    你想这样做:

    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()

    【讨论】:

      猜你喜欢
      • 2012-07-21
      • 1970-01-01
      • 1970-01-01
      • 2018-11-24
      • 1970-01-01
      • 2013-02-10
      • 2018-09-04
      • 2014-07-17
      • 1970-01-01
      相关资源
      最近更新 更多