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.
Try
System.getProperty("user.dir")
It returns the current working directory.
The current directory is not (necessarily) the directory the .class file is in. It's working directory of the process. (ie: the directory you were in when you started the JVM)
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.
*Note that this "directory" may actually be a jar file, depending on where the class was loaded from.
None of the above answer works for me. Here is what works for me.
Let's say your class name is Foo.java, to access to the myFile.txt in the same folder as Foo.java, use this code:
URL path = Foo.class.getResource("myFile.txt");
File f = new File(path.getFile());
reader = new BufferedReader(new FileReader(f));
Files in your project are available to you relative to your src folder. if you know which package or folder myfile.txt will be in, say it is in
----src
--------package1
------------myfile.txt
------------Prog.java
you can specify its path as "src/package1/myfile.txt" from Prog.java
If you know your file will live where your classes are, that directory will be on your classpath. In that case, you can be sure that this solution will solve your problem:
URL path = ClassLoader.getSystemResource("myFile.txt");
if(path==null) {
//The file was not found, insert error handling here
}
File f = new File(path.toURI());
reader = new BufferedReader(new FileReader(f));
Thanks #Laurence Gonsalves your answer helped me a lot.
your current directory will working directory of proccess so you have to give full path start from your src directory like mentioned below:
public class Run {
public static void main(String[] args) {
File inputFile = new File("./src/main/java/input.txt");
try {
Scanner reader = new Scanner(inputFile);
while (reader.hasNextLine()) {
String data = reader.nextLine();
System.out.println(data);
}
reader.close();
} catch (FileNotFoundException e) {
System.out.println("scanner error");
e.printStackTrace();
}
}
}
While my input.txt file is in same directory.
Try this:
BufferedReader br = new BufferedReader(new FileReader("java_module_name/src/file_name.txt"));
try using "."
E.g.
File currentDirectory = new File(".");
This worked for me
Related
I want to have a java app, where after starting the jar I get a file for example a test.txt within the same folder as the jar.
For example I click on the jar and in the same folder I get a test.txt file.
The below code works in eclipse and creates the file, but after an export to jar, no file is produced.
Would be very happy if you could help.
public class FileWriterTest {
public static void main(String[] args) {
String fileName = "test.txt";
try(
FileWriter fileWriter = new FileWriter(fileName);
BufferedWriter writer = new BufferedWriter(fileWriter);
) {
writer.write("Hello");
} catch(IOException e) {
e.printStackTrace();
}
}
}
With System.getProperty("user.dir") you can get the current "working directory".
If you want to create a file in that specific directory you could use the following code:
String workingDirectory = System.getProperty("user.dir");
File file = new File(working directory + File.separator + "filename.txt");
file.createNewFile();
If you are running as java -jar yourjar.jar, it will not take the additional classpath.
You need to add your jar and location where file resided in classpath and call java command for Main class
example
Linux
java -classpath .:path_dir_with_jar/*:path_to_file MainClass
Windows
java -classpath .;path_dir_with_jar/*;path_to_file MainClas
Finally can read as
InputStream in = this.getClass().getClassLoader()
.getResourceAsStream("SomeTextFile.txt")
;
I am new to Stack Overflow and fairly new to programming, so hopefully this makes sense. I am writing a java program that creates a file in a specific directory. My program works on Windows and creates a file in the right location, but it does not work on Mac. I have tried changing the backslashes to a single forward slash, but that doesn't work. How should I change the code so that it works for Mac or ideally for both? I've put some of the code below.
Thanks in advance!
Class that creates new path for file:
try{
//Create file path
String dirpath = new ReWriterRunner().getPath()+"NewFiles";
//Create directory if it doesn't exist
File path = new File(dirpath);
if (!path.exists()) {
path.mkdir();
}
//Create file if it doesn't exist
File readme = new File(dirpath+"\\README.md");
if (!readme.exists()) {
readme.createNewFile();
}
Method that gets user input on where to put file:
public static String getPath(){
String s;
Scanner in = new Scanner(System.in);
System.out.println("Enter the directory name under which the project files are stored.");
System.out.println("Example: C:\\Users\\user\\work\\jhipstertesting)");
System.out.println("Use double slashes when typing.");
s = in.nextLine();
return s;
}
you can use system properties to identify the system you are currently operating on ..
more info at https://docs.oracle.com/javase/tutorial/essential/environment/sysprop.html
but i would prefer using NIO. but that is your choice
https://docs.oracle.com/javase/tutorial/essential/io/fileio.html
Forward slash "/" must be used to get the file path here. for ex.> Use:
File f = new File("/Users/pavankumar/Desktop/Testing/Java.txt");
f.createNewFile();
I'm trying to learn more about how to read files in Java.
Currently I have some code that will read a file from the same directory:
File file = new File(getClass().getResource(fileName).getPath());
try (Scanner scanner = new Scanner(file)) {
while (scanner.hasNextLine()) {
String line = scanner.nextLine();
result.append(line).append("\n");
}
scanner.close();
} catch (IOException e) {
e.printStackTrace();
}
My issue is when I try to move my file into the resources directory.
File file = new File(getClass().getClassLoader().getResource(fileName).getFile());
I can read the file from the resources directory with an InputStream, but I'm trying to avoid doing that way. The file variable is what I would expect to work, but it doesn't.
Does anyone have advice on where I should go from here?
File file = new File(getClass().getResource("/"+fileName).getFile());
if the file is at the root of src/main/resources folder and you use Maven.
This is how I ended up solving this issue:
ClassLoader classLoader = getClass().getClassLoader();
File file = new File(classLoader.getResource("main/resources/" + fileName).getFile());
Could you try the following?
ClassLoader classLoader = ClassLoader.getSystemClassLoader();
File file = new File(classLoader.getResource(fileName).getFile());
I saved the text1.txt file in the same folder as the Algo.java file is in. But i get a Filenotfoundexception and i can't find any reason for that.
import java.io.*;
import java.util.logging.Level;
java.util.logging.Logger;
public class Algo{
static void naive(){
BufferedReader file1;
try{
file1=new BufferedReader(new FileReader("text1.txt"));
String T=file1.readLine();
System.out.println(T);
}
catch (FileNotFoundException ex) {
Logger.getLogger(Algoq1.class.getName()).log(Level.SEVERE, null, ex);
} catch (IOException ex) {
Logger.getLogger(Algoq1.class.getName()).log(Level.SEVERE, null, ex);
}
}
public static void main(String args[]){
Algo.naive();
}
}
Put resources separately form your code to make it manageable and reusable for other different package's classes also.
Try with other options.
// Read from same package
InputStream in = Algoq1.class.getResourceAsStream("text1.txt");
// Read from resources folder parallel to src in your project
File file = new File("resources/text1.txt");
// Read from src/resources folder
InputStream in = Algoq1.class.getResourceAsStream("/resources/text1.txt");
"I saved the text1.txt file in the same folder as the Algo.java file is in. But i get a Filenotfoundexception and i can't find any reason for that"
Then read the file from the class path. You can get an InputStream from Algo.class.getResourceAsStream()
InputStream is = Algo.class.getResourceAsStream("text1.txt");
BufferedReader br = new BufferedReader(new InputStreamReader(is));
When you try to read it as a File, which is the case when use FileReader(String path), file will be search within the file system, and in your IDE the search will begin from the working directory that is specified (normally the project root). So for the FileReader to work, with just the name of the file passed, the file should be in the working directory.
Depending on the requirements, whether the application is specific to your system or should be distributed on other systems, you need to make the decision whether the file should be read from the class path, or the file system.
I have a properties file contains the file name only say file=fileName.dat. I've put the properties file under the class path and could read the file name(file.dat) properly from it in the mainClass. After reading the file name I passed the file name(just name not the path) to another class under a package say pack.myClass to read that file. But the problem is pack.myClass could not get the file path properly. I've put the file fileName.dat both inside and outside the packagepack but couldn't make it work.
Can anybody suggest me that where to put the file fileName.dat so I can read it properly and the whole application would be portable too.
Thanks!
The code I'm using to read the config file and getting the file name:
Properties prop = new Properties();
InputStream in = mainClass.class.getResourceAsStream("config.properties");
prop.load(in);
in.close();
myClass mc = new myClass();
mc.readTheFile(prop.getProperty("file"));
/*until this code is working good*/
Then in myClass which is under package named pack I am doing:
public void readTheFile(String filename) throws IOException {
FileReader fileReader = new FileReader(filename); /*this couldn't get the file whether i'm putting the file inside or outside the package folder */
/*after reading the file I've to do the BufferReader for further operation*/
BufferedReader bufferedReader = new BufferedReader(fileReader);
I assume that you are trying to read properties file using getResource method of class. If you put properties file on root of the classpath you should prefix file name with '/' to indicate root of classpath, for example getResource("/file.dat"). If properties file is under the same folder with the class you on which you invoke getResource method, than you should not use '/' prefix.
When you use a relative file name such as fileName.dat, you're asking for a file with this name in the current directory. The current directory has nothing to do with packages. It's the directory from which the JVM is started.
So if you're in the directory c:\foo\bar when you launch your application (using java -cp ... pack.MyClass), it will look for the file c:\foo\bar\fileName.dat.
Try..
myClass mc = new myClass();
InputStream in = mc.getClass().getResourceAsStream("/pack/config.properties");
..or simply
InputStream in = mc.getClass().getResourceAsStream("config.properties");
..for the last line if the main is in myClass The class loader available in the main() will often be the bootstrap class-loader, as opposed to the class-loader intended for application resources.
Class.getResource will look in your package directory for a file of the specified name.
JavaDocs here
Or getResourceAsStream is sometimes more convenient as you probably want to read the contents of the resource.
Most of the time it would be best to look for the "fileName.dat" somewhere in the "user.home" folder, which is a system property. First create a File path from the "user.home" and then try to find the file there. This is a bit of a guess as you don't provide the exact user of the application, but this would be the most common place.
You are currently reading from the current folder which is determined by
String currentDir = new File(".").getAbsolutePath();
or
System.getProperty("user.dir")
To read a file, even from within a jar archive:
readTheFile(String package, String filename) throws MalformedURLException, IOException
{
String filepath = package+"/"+filename;
// like "pack/fileName.dat" or "fileName.dat"
String s = (new SourceBase()).getSourceBase() + filepath;
URL url = new URL(s);
InputStream ins = url.openStream();
BufferedReader rdr = new BufferedReader(new InputStreamReader(ins, "utf8"));
do {
s = rdr.readLine();
if(s!= null) System.out.println(s);
}
while(s!=null);
rdr.close();
}
with
class SourceBase
{
public String getSourceBase()
{
String cn = this.getClass().getName().replace('.', '/') + ".class";
// like "packagex/SourceBase.class"
String s = this.getClass().getResource('/' + cn).toExternalForm();
// like "file:/javadir/Projects/projectX/build/classes/packagex/SourceBase.class"
// or "jar:file:/opt/java/PROJECTS/testProject/dist/
// testProject.jar!/px/SourceBase.class"
return s.substring(0, s.lastIndexOf(cn));
// like "file:/javadir/Projects/projectX/build/classes/"
// or "jar:file:/opt/java/PROJECTS/testProject/dist/testProject.jar!/"
}
}