Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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)

like image 260
meiryo Avatar asked Sep 13 '12 12:09

meiryo


2 Answers

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();
            }
        }
    }
}
like image 141
swemon Avatar answered Sep 28 '22 02:09

swemon


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

like image 25
Łukasz Tomaszewski Avatar answered Sep 28 '22 02:09

Łukasz Tomaszewski