The system cannot find the file specified in java

前端 未结 8 833
轮回少年
轮回少年 2020-11-28 08:52

I am making a program that opens and reads a file. This is my code:

import java.io.*;

public class FileRead{
    public static void main(String[] args){
           


        
相关标签:
8条回答
  • 2020-11-28 09:15

    You need to give the absolute pathname to where the file exists.

            File file = new File("C:\\Users\\User\\Documents\\Workspace\\FileRead\\hello.txt");
    
    0 讨论(0)
  • 2020-11-28 09:15

    How are you running the program?

    It's not the java file that is being ran but rather the .class file that is created by compiling the java code. You will either need to specify the absolute path like user1420750 says or a relative path to your System.getProperty("user.dir") directory. This should be the working directory or the directory you ran the java command from.

    0 讨论(0)
  • 2020-11-28 09:20

    I have copied your code and it runs fine.

    I suspect you are simply having some problem in the actual file name of hello.txt, or you are running in a wrong directory. Consider verifying by the method suggested by @Eng.Fouad

    0 讨论(0)
  • 2020-11-28 09:21

    In your IDE right click on the file you want to read and choose "copy path" then paste it into your code.

    Note that windows hides the file extension so if you create a text file "myfile.txt" it might be actually saved as "myfile.txt.txt"

    0 讨论(0)
  • 2020-11-28 09:29

    First Create folder same as path which you Specified. after then create File

    File dir = new File("C:\\USER\\Semple_file\\");
    File file = new File("C:\\USER\\Semple_file\\abc.txt");
    
    if(!file.exists())
    {
        dir.mkdir();
        file.createNewFile();
        System.out.println("File,Folder Created.);
    }
    
    0 讨论(0)
  • 2020-11-28 09:32

    Try to list all files' names in the directory by calling:

    File file = new File(".");
    for(String fileNames : file.list()) System.out.println(fileNames);
    

    and see if you will find your files in the list.

    0 讨论(0)
提交回复
热议问题