So I'm trying to read in from a config file in my Eclipse project, but it can't locate the file. Here's my code.
public void readConfigFile () {
//URL url = Test.class.getClassLoader().getResource("myfile.txt");
//System.out.println(url.getPath());
URL url = getClass().getResource("/config");
System.out.println(url);
try {
BufferedReader read = new BufferedReader(new FileReader(url.toString()));
//read in values for constants from config file
System.out.println(BASE_URL);
BASE_URL = read.readLine().split("\t")[1];
System.out.println(BASE_URL);
read.close();
}
catch (Exception e)
{
System.out.println("Read from config file failed. Terminating program");
System.out.println(e);
System.exit(1);
}
}
When I run, it prints the url variable as:
/Users/myname/Development/workspace/New_API/bin/config
But it fails to find the file when running the BufferedReader command. I get:
Read from config file failed. Terminating program
java.io.FileNotFoundException:
file:/Users/myname/Development/workspace/New_API/bin/config.txt (No such file or directory)
When I go to the bin directory of my code however, the config file is there. In the root bin directory, following the exact path given by the URL. What is messing Eclipse up?
When getting a resource from the class loader, you're getting it from the classpath, not from the file system. If your application was packaged as a jar, you wouldn't have access to the resource through the File or FileInputStream APIs since the resource is part of the archive. Instead, you can access the input stream of the resource like so:
URL url = getClass().getResource("/config");
BufferedReader read = new BufferedReader(new InputStreamReader(url.openStream()));
// more...
Related
I have a certain requirement where I need to copy files from Unix server to Windows Shared Drive. I am developing the necessary code for this in Java. I am a beginner so please excuse me for this basic question.
I have my source path in my config file. So, I am using the below code to import my config file and set my variable. My Project has config.properties file attached to it.
public static String rootFolder = "";
Properties prop = new Properties();
InputStream input = null;
try {
input = new FileInputStream("config.properties");
} catch (FileNotFoundException e) {
e.printStackTrace();
System.out.println("Config files not able to set properly for Dest Folder");
}
try {
prop.load(input);
rootFolder = prop.getProperty("Dest_Root_Path");
System.out.println("Destination Folder is being initialized to - "+rootFolder);
} catch (IOException e) {
e.printStackTrace();
System.out.println("Destination Path not set properly");
}
When I am doing this I am getting an error saying the file is not found.
java.io.FileNotFoundException: config.properties (No such file or directory)
at java.io.FileInputStream.<init>(FileInputStream.java:158)
at java.io.FileInputStream.<init>(FileInputStream.java:113)
Exception in thread "main" java.lang.NullPointerException
at java.util.Properties.load(Properties.java:357)
I am triggering this jar using a unix ksh shell. Please provide guidance to me.
Put your config file somewhere within the classpath. For example, if it's a webapp, in WEB-INF/classes. If it isn't a webapp, create a folder outside the project, put the file there, and set the classpath so the new folder is in it.
Once you have your file in the classpath, get it as a resource with getResourceAsStream():
InputStream is = MyProject.class.getResourceAsStream("/config.properties");
Don't forget the slash / before the filename.
I wrote a Java Application using NetBeans. It reads text file from the project's root directory. When I run the jar file from command line it can't find the required file.
String inputFile = "input.txt";
Properties prop = new Properties();
String targetFormat = null;
try {
InputStream input = new FileInputStream("book-info-converter.properties");
prop.load(input);
targetFormat = prop.getProperty("targetFormat");
}
catch(IOException ex){
System.out.println("file not found");
}
How to solve this problem? Where to put my file so that the application can find that when running jar from command line?
Place the book-info-converter.properties in the src folder (it's better in resources if you have). Then you can load it as resource stream like
InputStream input = YourClass.class.getResourceAsStream("/book-info-converter.properties");
I am unable to load in a txt file on the command line but in eclipse it loads fine. Below is the code that loads in the file.
try{
BufferedReader in =
new BufferedReader(new FileReader("piratewords.txt"));
int count = 0;
while (in.ready()) { //while there is another line in the input file
game.puzzles[count] = in.readLine(); //get line of data
count++; //Increment CWID counter
}
in.close();
}
catch(IOException e){
System.out.println("Error during reading/writing");
}
Kindly give the absolute path of file in FileReader("absolute path").Or place the txt file where your java source file is present.
piratewords.txt file should be available inside a classpath or else we need to specify
full absolute path of the location where the file is.
looks like when you are running it from command line, you are not keeping this file
in the required classpath.
better give absolute path of the file and check it.
absolute path like below
BufferedReader in = new BufferedReader(
new FileReader("C:/Users/karibasappagc/Desktop/piratewords.txt"));
and make sure file existence in the specified path.
This happens because the file is not in the classpath of your JVM.
Check Eclipse running classpath or use absolute path for your piratewords.txt. The file should at least be in your classes folder or you should add the folder it's in, in your classpath.
I can read texts and write them to console however when i install this application to another computer wherever it is installed I dont want to change the path of the txt file. I want to write it like
BufferedReader in = new BufferedReader(new FileReader("xxx.txt"));
I don't want to:
BufferedReader in = new BufferedReader(new FileReader("C:\\Users\\abcde\\Desktop\\xxx.txt"));
is there any way to show this txt file? By the way I put this txt file inside the sources but it cant read!
First get the default application path then check if file exist if exist continue if not close application.
String path = System.getProperty("user.dir");
System.out.println(path + "\\disSoruCevap.txt");
File file = new File(path + "\\disSoruCevap.txt");
if (!file.exists()) {
System.out.println("System couldnt file source file!");
System.out.println("Application will explode");
}
EDIT*
Please prefer one of the answer using resource streams, as you will
see from comments using user.dir is not safe in every case.
You are looking for :
BufferedReader in = new BufferedReader(getClass().getResourceAsStream("/xxx.txt"));
This will load xxx.txt from your jar file (or any jar file in your class path that has that file inside its root directory).
URL fileURL= yourClassName.class.getResource("yourFileName.extension");
String myURL= fileURL.toString();
now you don't need long path name PLUS this one is dynamic in nature i.e., you can now move your project to any pc, any drive.This is because it access URL by using your CLASS location not by any static location (like c:\folder\ab.mp3, then you can't access that file if you move to D drive because then you have to change to D:/folder/ab.mp3 manually which is static in nature)(NOTE: just keep that file with your project)
You can use fileURL as: File file=new File(fileURL.toURI());
You can use myURL as: Media musicFile=new Media(myURL); //in javaFX which need string not url of file
InputStream input = Class_name.class.getResourceAsStream("/xxx.txt");
InputStreamReader inputReader = new InputStreamReader(input);
BufferedReader br = new BufferedReader(inputReader);
String line = null;
try {
while((line = br.readLine())!=null){
System.out.println(line);
}
} catch (IOException ex) {
ex.printStackTrace();
}
You don't need to write or mention long path. Using this code Class_name.class.getResourceAsStream("/xxx.txt"), you can easily get your file.
BufferedReader in = new BufferedReader(new FileReader("xxx.txt")); works fine because when you run your application on an IDE, xxx.txt apparantly is lying in Java's working directory.
Working directory is an operating system feature and it can not be changed.
There are a few ways to deal with this.
1 - use file constructor new File(parent, filename); and load parent using a public static final constant or a property (either passed from command line or otherwise)
2 - or use InputStream in = YourClass.class.getClassLoader().getResourceAsStream("xxx.txt"); - provided your xxx.txt file is packaged under same location as YourClass
Try:
InputStream is = ClassLoader.getSystemResourceAsStream("xxx.txt");
BufferedReader in = new BufferedReader(new InputStreamReader(is));
Depending on where exactly is your file compared to the root of your classpath, you may have to replace xxx.txt3 with /xxx.txt.
My file paths are like this:
public final static String COURSE_FILE_LOCATION = "src/main/resources/courses.csv";
public final static String PREREQUISITE_FILE_LOCATION = "src/main/resources/prerequisites.csv";
This doesn't work. So I delete the .iml file, .idea and target folder from the project and reload them.
Read the correct path like this:
This would work then.
I want to be able to have my paths work on any server not just my dev box.
Right now I declear the full path of the file name as such on my local drive.
filename = "H:\test\SourceCode\sample\src\file.txt"
try
{
BufferedReader in = new BufferedReader(new FileReader(fileName));
line = in.readLine();
in.close();
}
catch (IOException e) {
log.error("Exception Message", e);
}
How can I set the file path so when I create the .war file I can use it on any server. Such as filename = "src/file.txt" (This doesn't work for me)
Two usual ways:
getClass().getResourceAsStream("/..") - resolves the path relative to the classpath - that is, WEB-INF/classes (and jar files)
getServletContext().getResourceAsStream("/..") resolves the path relative to the webapp root. That is - webapps/applicationname