Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java, reading a file from current directory?

Tags:

java

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.

like image 597
Saobi Avatar asked Sep 26 '09 03:09

Saobi


People also ask

How do I read files in the same directory?

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.

How do you mention the current directory in Java?

In Java, we can use System. getProperty("user. dir") to get the current working directory, the directory from where your program was launched.

How do you read the contents of a file in Java?

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.

How do you load a file in Java?

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.


1 Answers

Try

System.getProperty("user.dir") 

It returns the current working directory.

like image 155
Joonas Pulakka Avatar answered Sep 17 '22 17:09

Joonas Pulakka