将我的文件打印到控制台时遇到问题

问题描述

我有一个数据结构分配,代码必须从文本文件中读取文本数据并将其打印到屏幕上。我写的代码说构建成功但文本文件本身不打印。我该怎么办?

import java.util.Scanner;
import java.io.IOException;
import java.io.FileInputStream

public class readFile{
    public static void main(String[] args) throws IOException {
        FileInputStream fileByteStream = null;
        Scanner file = null;
        int textFile;
        try{
            fileByteStream = new FileInputStream("file1.txt");
            file = new Scanner(fileByteStream);
            while(file.hasNextInt()){
                textFile = file.nextInt();
                System.out.println("file1.txt");
            }
        }
        catch(IOException e){
    
        }
    }
}

解决方法

System.out.println("file1.txt"); 替换为 System.out.println(textFile);

,

如果您将“file1.txt”保存在正确的位置,这应该可以工作。照原样,您只是传递字符串“file1.txt”而不是尚未创建的文件对象。 (见下面这段代码的第 13 行)

import java.util.Scanner;
import java.io.IOException;
import java.io.File;
import java.io.FileInputStream;

    public class readFile
    {
      public static void main(String[] args) throws IOException 
      {
        FileInputStream fileByteStream = null;
        Scanner file = null;
        int textFile;
        File file1 = new File("file1.txt");
      try
      {
        fileByteStream = new FileInputStream(file1); 
        file = new Scanner(fileByteStream);
        System.out.println("Reading file...");
        while(file.hasNextInt())
        {
          textFile = file.nextInt();
          System.out.println(textFile);
          System.out.println("Scanning a line..");
        }
        file.close();
      }
      catch(IOException e)
      {
        System.out.println("Exception handled");
        e.printStackTrace();
      }
      }
    }
,

您可以使用打印语句来帮助查看代码中断的位置。看起来您有 IO 异常(输入/输出)。此外,您应该关闭 Scanner 对象。

    import java.util.Scanner;
    import java.io.IOException;
    import java.io.FileInputStream;

    public class readFile
    {
      public static void main(String[] args) throws IOException 
      {
        FileInputStream fileByteStream = null;
        Scanner file = null;
        int textFile;
     
      try
      {
        fileByteStream = new FileInputStream("file1.txt"); 
        file = new Scanner(fileByteStream);
        System.out.println("Reading file...");
        while(file.hasNextInt())
        {
          textFile = file.nextInt();
          System.out.println(textFile);
          System.out.println("Scanning a line..");
        }
        file.close();
      }
      catch(IOException e)
      {
        System.out.println("Exception handled");
      }
      }
    }

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...