What is the root place of FileReader searching for files? - java

I've tried to load file to use by scanner like this:
try {
Scanner scanner = new Scanner(new FileReader("map.txt"));
}catch (FileNotFoundException e) {
e.printStackTrace();
}
But I get the FileNotFoundException error even thought I place map.txt file in class folder. Also I created special folder and marked it as a resources root in IntelliJ IDEA but still it doesn't work. How can I know where FileReader is searching for file then?

This might help you. Use File#getAbsolutePath() to check for the path.
File reader = new File("abc.txt");
System.out.println(reader.getAbsolutePath());
Some more ways to read from project
// Read from resources folder parallel to src in your project
File file1 = new File("resources/abc.txt");
System.out.println(file1.getAbsolutePath());
// Read from src/resources folder
File file2 = new File(getClass().getResource("/resources/abc.txt").toURI());
System.out.println(file2.getAbsolutePath());

Related

Read file from another package - Java

I'm trying to access a file from another package:
-Using LoadDatabase from Main package to access DB.txt from resources.
Image Here
When I do
File file = new File("/com/Convocatoria/resources/DB.txt");
Scanner sc = new Scanner(file);
It gives me this error
Unhandled exception type FileNotFoundException
Don't Use absolute path use getResourceAsStream method
I dont know which IDE you are using if you specify the path like this it jvm will look for file from the root of your project but your file is precent in your rootproject->src->under some packages so it is best to use getResouceAsStream because when you build it or run it all the .class files and property files will go under the class path so we know that our file will be in classpath So we can easily read the file using getResourceAsStream for eg:-
you are reading the file from MainWindow.java class
use the below code
InputStream is =MainWindow.class.getResourceAsStream("/Convocatoria/resources/DB.txt")
from this inputstream you use FileInputStream or whatever you want to read the file
Since you are loading data from within your classpath, you can use resources instead:
String resourceName = "/com/Convocatoria/resources/DB.txt";
URL res = LoadDatabase.class.getResource(resourceName);
System.out.println("resource found at url="+res);
InputStream is = LoadDatabase.class.getResourceAsStream(resourceName);
Scanner s = new Scanner(is);
//read..
//after using it, close your stream
is.close();
File constructor will throw a FileNotFoundException when it fails to find the file with specific path. You need to surround it with a try-catch block that catches the mentioned exception:
File file = null;
Scanner sc = null;
try{
file = new File("/com/Convocatoria/resources/DB.txt");
sc = new Scanner(file);
// do something with opened file
} catch(FileNotFoundException ex){
ex.printStackTrace();
}

create bunch of files in particular directory

I am trying to create lot of files in particular directory. If directory doesn't exist then it should create the directory and create bunch of files in it.
Whereever my program is running, it should create a "files" directory if it is not there and inside this "files" folder, I want to create bunch of files in it.
I have my below code but it looks like it is creating bunch of folders instead of one folder and all the files in that folder. What wrong I am doing?
for (Entry<String, String> entry : tasks.entrySet()) {
// looks like something is wrong here but can't figure out what wrong I am doing?
File file = new File("files/" + entry.getKey());
file.mkdirs();
try (BufferedWriter writer =
new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file),
StandardCharsets.UTF_8))) {
writer.write(entry.getValue());
} catch (IOException ex) {
// log error
}
}
For example, you're trying to create file C:\Stuff\Things\other.txt
With your current code, you create the folder C:\Stuff\Things\other.txt\
When you attempt to write to the file, moo.txt, it cannot, because you put a folder there (...\other.txt\)
Instead, create the folders up to, but not including the file name, before writing your file (C:\Stuff\Things\)
File file = new File(...);
file.getParentFile().mkdirs();
try(BufferedWriter ...

IntelliJ IDE - FileNotFound exception from root project directory

I used an ObjectOutputStream to write an object to a file in the same directory as my project's .iml file. The file exists. For some reason, I can't read it using a FileInputStream. I recieve a FileNotFound exception at line 2.
My code is as follows:
File sceneFile=new File("scene.dodge");
FileInputStream fin=new FileInputStream(sceneFile);
ObjectInputStream in=new ObjectInputStream(fin);
return (Scene)(in.readObject());
I've made sure the file scene.dodge is in the project root directory. Any suggestions? I've tried messing around with compiler resource patterns, but I have no idea if that'll do anything. I'm simply stumped.
To read the file from the current directory you need to use ClassLoader#
getResource method.
Load the file like this
URL dodgeSceneURL = classLoader.getResource("scene.dodge");
File sceneFile = new File(dodgeSceneURL.toURI());
FileInputStream fin = new FileInputStream(sceneFile);

Can't find resources runnable jar

I can't load an resource file after extracting a project as a runnable jar.
It works in Eclipse but after exporting it throws a FileNotFoundException.
I have tried to put the res folder next to the .jar file but nothing helps. I've tried with JarSplice and got it running with all the libraries but it stops with the resource file. The object file is located in a source folder.
What can I do?
Code
FileReader fr = null;
try {
fr = new FileReader(new File("res/" + fileName + ".obj"));
} catch (FileNotFoundException e) {
System.err.println("Couldn't load object file!");
e.printStackTrace();
}
EDIT: By opening the runnable .jar file in 7zip I can see that the whole /res folder has disappeared during the exporting and the files in the directory now lies directly in the root folder of the .jar file.
Based on your code, the res folder should be placed directly off the present working directory, which should be the directory where you are running the Java command from. For an example, see this question on how to determine the current working directory from inside Java.
Use Path instead of new File(string).
FileReader fr = null;
try {
fr = new FileReader(Paths.get("res/" + fileName + ".obj").toFile());
} catch (FileNotFoundException e) {
System.err.println("Couldn't load object file!");
e.printStackTrace();
}

How to use the .txt, .xml and .properties file inside the executable jar?

I have a java project which will read a txt file and process that.
For production purpose, I will need to generate an executable jar which contains this txt file.
I use the code like:
BufferedReader br = new BufferedReader(new FileReader("src/txt_src/sample.txt"));
My jar contains txt_src/sample.txt, but can't use it. Instead, if I put a src directory which has src/txt_src/sample.txt structure, the jar works.
It will be better to generate directly by Eclipse.
Thanks in advance!
Treat the file as a resource and give the path as the package hierarchy.
http://docs.oracle.com/javase/7/docs/api/java/lang/Class.html#getResourceAsStream%28java.lang.String%29
You can then take the InputStream and wrap it in an InputStreamReader that is wrapped in a BufferedReader. Wrap it in a BufferedInputStream if you need to define the encoding, which you should do.
new BufferedReader(new InputStreamReader(new BufferedInputStream(this.getResourceAsStream("myPackage/myFile.txt")), "UTF-8"));
Put your files in the assets Folder of your Project and use them with:
InputStream stream = null;
try {
stream = getAssets().open("sample.txt");
}
catch (IOException e) {
e.printStackTrace();
}

Categories