Hi, is there a way to make FileInputStream read hello.txtin the same directory without specifying a path?
hello.txt
package hello/ helloreader.java hello.txt
My error message: Error: .\hello.txt (The system cannot find the file specified)
Error: .\hello.txt (The system cannot find the file specified)
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(); } } } }
You can use YourClassName.class.getResourceAsStream("Filename.txt"), but your text file should be in the same directory / package as your file YourClassName.
YourClassName.class.getResourceAsStream("Filename.txt")
YourClassName
"hello.txt", . , , - .
hello.txt, hello.txt , java, . Java:
java
System.out.println(System.getProperty("user.dir"));
, , java hello.helloreader, , hello.txt:
java hello.helloreader
new FileInputStream("hello/hello.txt")
you can try System.getProperty ("dir") to show your current directory and you will know how to write the file path