使用Scanner读取文本文件(Java)

huangapple go评论68阅读模式
英文:

Reading Text File WIith Scanner (Java)

问题

import java.util.Scanner;
import java.io.File;
import java.io.FileNotFoundException;

public class Driver {

    public static void main(String[] args) {

        String fileName = "p1.txt";
        Scanner inputStream = null;
        System.out.println("The file " + fileName + "\ncontains the following lines: \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();
    }

}

"p1.txt"文件中的内容如下:

p, -4, 5
q, 19, 8
r, 3, 0
x, 7.4, -1
y, -2.3,  -16.5
z, 0, 1

出于某种原因,我的代码无法读取文本文件,并给出以下输出:

The file p1.txt
contains the following lines: 

Error opening the file p1.txt

我不确定我需要做什么。
英文:

My Text file is called p1 and it contains:

p, -4, 5
q, 19, 8
r, 3, 0
x, 7.4, -1
y, -2.3,  -16.5
z, 0, 1

My code is:

import java.util.Scanner;
import java.io.File;
import java.io.FileNotFoundException;

public class Driver {

	public static void main(String[] args) {
		
		String fileName = "p1.txt";
		Scanner inputStream = null;
		System.out.println("The file " + fileName + "\ncontains the following lines: \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();
	}

}

For some reason my code can't read my text file and gives me the following output:

The file p1.txt
contains the following lines: 

Error opening the file p1.txt

I'm not sure what I need to do.

答案1

得分: 1

这是因为您的文件 "p1.txt" 不存在。请检查文件的位置。它应该放在同一个目录中。

英文:

This is because your file "p1.txt" does not exists. Check the location of your file. It should be placed in same directory.

答案2

得分: 1

确保txt文件与项目在同一个文件夹中,如果不在,请提供路径。

英文:

Make sure that txt file is in the same folder as the project, if not give a path to it.

huangapple
  • 本文由 发表于 2020年9月3日 15:56:55
  • 转载请务必保留本文链接:https://go.coder-hub.com/63719225.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定