I want a java program that reads a user specified filename from the current directory (the same directory where the .class file is run).
In other words, if the user specifies the file name to be "myFile.txt", and that file is already in the current directory:
reader = new BufferedReader(new FileReader("myFile.txt"));
does not work. Why?
I'm running it in windows.
You can load files from the same directory* as the . class file with getResourceAsStream(). That'll give you an InputStream which you can convert to a Reader with InputStreamReader.
In Java, we can use System. getProperty("user. dir") to get the current working directory, the directory from where your program was launched.
There are several ways to read a plain text file in Java e.g. you can use FileReader, BufferedReader, or Scanner to read a text file. Every utility provides something special e.g. BufferedReader provides buffering of data for fast reading, and Scanner provides parsing ability.
Example 1: Java Program to Load a Text File as InputStream txt. Here, we used the FileInputStream class to load the input. txt file as input stream. We then used the read() method to read all the data from the file.
Try
System.getProperty("user.dir")
It returns the current working directory.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With