FileInputStream ("hello.txt") does not work unless I specify an absolute path (C: \ User \ Documents, etc.),

Hi, is there a way to make FileInputStream read hello.txtin the same directory without specifying a path?

package hello/
    helloreader.java
    hello.txt

My error message: Error: .\hello.txt (The system cannot find the file specified)

+5
source share
5 answers

You can read the file with a relative path, for example.

File file = new File("./hello.txt");
  • Yourproject

    -> bin

    -> hello.txt

    -. > CLASSPATH

    -. > Project

Here is the work

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

public class fileInputStream {

    public static void main(String[] args) {

        File file = new File("./hello.txt");
        FileInputStream fis = null;

        try {
            fis = new FileInputStream(file);

            System.out.println("Total file size to read (in bytes) : "
                    + fis.available());

            int content;
            while ((content = fis.read()) != -1) {
                // convert to char and display it
                System.out.print((char) content);
            }

        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (fis != null)
                    fis.close();
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        }
    }
}
+10
source

You can use YourClassName.class.getResourceAsStream("Filename.txt"), but your text file should be in the same directory / package as your file YourClassName.

+9
source

"hello.txt", . , , - .

+3

hello.txt, hello.txt , java, . Java:

System.out.println(System.getProperty("user.dir"));

, , java hello.helloreader, , hello.txt:

new FileInputStream("hello/hello.txt")
+2

you can try System.getProperty ("dir") to show your current directory and you will know how to write the file path

0
source

All Articles