6

Hi is there any way I can get FileInputStream to read hello.txt in 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)

meiryo
  • 11,157
  • 14
  • 47
  • 52

5 Answers5

11

You can read file with relative path like.

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

    ->bin

    ->hello.txt

    ->.classpath

    ->.project

Here is works

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();
            }
        }
    }
}
swemon
  • 5,840
  • 4
  • 32
  • 54
10

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

Flavio
  • 11,925
  • 3
  • 32
  • 36
  • Thanks. Does this only happen for certain IDEs? I've tried good old text editor and command line and it works fine. – meiryo Sep 13 '12 at 12:53
  • This won't work if you are going to deploy a web project as a .war file that puts your Java classes in the WEB-INF/classes folder, which many commonly do now. – Fuzzy Analysis Apr 11 '15 at 08:11
4

When you open "hello.txt" you are opening a file in the current working directory of the process. i.e. where the program was run from, not where your jar is or some other directory.

Peter Lawrey
  • 525,659
  • 79
  • 751
  • 1,130
3

When you open your file with path hello.txt, the file hello.txt should be in the same directory of where you execute the java command, that is the working directory. And you can use the following code to print the working directory when you run a Java program:

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

Suppose you execute your code like this java hello.helloreader, then you should use the following path to get the hello.txt:

new FileInputStream("hello/hello.txt")
khotyn
  • 944
  • 1
  • 8
  • 16
0

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

倪玉哲
  • 27
  • 1