简体   繁体   中英

Reading Text File WIith Scanner (Java)

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.

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

确保 txt 文件与项目在同一个文件夹中,如果没有给出它的路径。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM