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.
Related
I want to open a .java text file and insert a new package name at the top of the file. After some research to this I found out that I have to create a new file insert the new Package name and copy everything from my old file. So far so good.
1) 1st Problem either I am not doing it correct, but how am I able to copy line endings in the correct way? I kinda have the feeling that by copying I lose them, not sure but that since I was more focused on my other Problem
2) The file I am trying to rename just doesn't get renamed, therefore resulting in the problem, that all files in which I want to insert the new package are getting named the same and therefore I am left with the last file with the wrong name. Resulting in a loss of all my other files
private static String insertPackage(File file) throws IOException {
//creating package name
File parent = new File(file.getParent());
String packageName = "package " + parent.getName() + ";\n";
//copy old file
File buffer = new File(parent.getPath()+"\\buffer.java");
Charset charset = Charset.forName("UTF-8");
BufferedReader br = Files.newBufferedReader(file.toPath(),charset);
BufferedWriter bw = Files.newBufferedWriter(buffer.toPath(),charset);
bw.write(packageName,0,packageName.length());
String line;
while((line = br.readLine()) != null){
if(!line.startsWith("package ")) {
bw.write(line, 0, line.length());
}
}
//rename new file
// String filepath = file.getPath();
// File rename = new File(filepath);
boolean renamed = true;
if(file.delete()) {
renamed = buffer.renameTo(file);
}
bw.flush();
bw.close();
br.close();
if(!renamed){
return file.getPath();
}
return "";
}
The return value is just there to have a name in case something is failing. So right now everything.
This is just the function to insert the package name, delete the old package name and, copy everything else into the new file. After that it should delete the old file and rename the new one.
You are loosing the line breaks, because readLine strips them, but you never write any out to the file. You will need to add a \n (or \r\n depending on your needs) to every line you write to the new file. You can use BufferedWriter#newLine for writing the platform-dependent line separator.
The new file does not get renamed, because your file streams are still open for both files when you try to rename it. Moreover File#renameTo is highly platform dependent (as noted in the documentation) and might not be able to overwrite existing files, I recommend you switch over to Files#move, where you can specify StandardCopyOption.REPLACE_EXISTING.
I can also recommend to fully switch over to the NIO API and not use java.io.File at all, instead use Path directly
Note also that it is a good choice to use try-with-resources instead of manually closing streams, especially when dealing with multiple streams at once.
I am developing a NetBeans module where I have a Java package called testand another package called test.templates. I want to read a text file which is in the test.templates package from a Java file in the test package. I tried in several ways, but it gives a FileNotFoundException exception:
BufferedReader br = new BufferedReader(new FileReader("templates/test.txt"));
BufferedReader br = new BufferedReader(new FileReader("/test/templates/test.txt"));
BufferedReader br = new BufferedReader(new FileReader("src/test/templates/test.txt"));
But none of these worked.. I want to use the relative path, not the absolute path. What should I do?
You will want to use getResource or getResourceAsStream.
Example on java2s.com:
http://www.java2s.com/Code/Java/Development-Class/Loadresourcefilerelativetotheclasslocation.htm
You should note somethings about relative path (Netbeans):
+ File: Default is project folder, means outside of src folder.
If you save to test.txt, it will generate: project/test.txt.
If you save to data/test.txt, ... project/data/test.txt
So if you want to load file, you just do it conversely. Like this, you should put your files in project/data/filename.txt. Then when code, you get path: data/filename.txt.
+ ImageIcon: I will share later if can.
+ Image(SplashScreen): I will share later.
getResource() returns a URL, so to extract the filename, you can try calling getFile().
The filepath you pass to getResource will be based on your netbeans package. Use a leading slash to denote the root of the classpath.
Example:
getResource(/db_files/table.csv).getFile()
try
{
BufferedReader br = new BufferedReader(new FileReader(getClass().getResource("/test/templates/test.txt").toString().substring(6)));
}
catch(Exception ee)
{
JOptionPane.showMessageDialog(this, ee);
}
I need to be able to access a file stored in a compiled jar file. I have figured out how to add the file to the project, but how would I reference it in the code? How might I copy a file from the jar file to a location on the user's hard drive? I know there are dozens of ways to access a file (FileInputStream, FileReader, ect.), but I don't know how to look inside itself.
You could use something like this:
InputStream is = this.getClass().getClassLoader().getResourceAsStream(fileFromJarFile);
If foo.txt was in the root of your JAR file, you'd use:
InputStream is = this.getClass().getClassLoader().getResourceAsStream("foo.txt");
assumes the class is in the same JAR file as the resource, I believe.
You can use getResource() to obtain a URL for a file on the classpath, or getResourceAsStream() to get an InputStream instead.
For example:
BufferedReader reader = new BufferedReader(new InputStreamReader(
this.getClass().getResourceAsStream("foo.txt")));
You could read the contents of a JAR file using the JarFile class.
Here's an example of how you could get a specific file from a JAR file and extract it:
JarFile jar = new JarFile("foo.jar");
String file = "file.txt";
JarEntry entry = jar.getEntry(file);
InputStream input = jar.getInputStream(entry);
OutputStream output = new FileOutputStream(file);
try {
byte[] buffer = new byte[input.available()];
for (int i = 0; i != -1; i = input.read(buffer)) {
output.write(buffer, 0, i);
}
} finally {
jar.close();
input.close();
output.close();
}
Just wanted to add that if we want to access file inside Jar that is located at the following path(only examples as resources loading is OS independent):
Windows:
c:\your-jar-file.jar\dir1\dir2\dir3\foo.txt
Linux:
/home/your-jar-file.jar/dir1/dir2/dir3/foo.txt
Will need to use following code(pay attention that there is NO "/"(forward-slash) character in the beginning of the path):
InputStream is = this.getClass().getClassLoader().getResourceAsStream("dir1/dir2/dir3/foo.txt");
Look at the JarFile class. Everything you need to get the InputStream of a specific entry in the jar file is there.
I have a project with 2 packages:
tkorg.idrs.core.searchengines
tkorg.idrs.core.searchengines
In package (2) I have a text file ListStopWords.txt, in package (1) I have a class FileLoadder. Here is code in FileLoader:
File file = new File("properties\\files\\ListStopWords.txt");
But I have this error:
The system cannot find the path specified
Can you give a solution to fix it?
If it's already in the classpath, then just obtain it from the classpath instead of from the disk file system. Don't fiddle with relative paths in java.io.File. They are dependent on the current working directory over which you have totally no control from inside the Java code.
Assuming that ListStopWords.txt is in the same package as your FileLoader class, then do:
URL url = getClass().getResource("ListStopWords.txt");
File file = new File(url.getPath());
Or if all you're ultimately after is actually an InputStream of it:
InputStream input = getClass().getResourceAsStream("ListStopWords.txt");
This is certainly preferred over creating a new File() because the url may not necessarily represent a disk file system path, but it could also represent virtual file system path (which may happen when the JAR is expanded into memory instead of into a temp folder on disk file system) or even a network path which are both not per definition digestable by File constructor.
If the file is -as the package name hints- is actually a fullworthy properties file (containing key=value lines) with just the "wrong" extension, then you could feed the InputStream immediately to the load() method.
Properties properties = new Properties();
properties.load(getClass().getResourceAsStream("ListStopWords.txt"));
Note: when you're trying to access it from inside static context, then use FileLoader.class (or whatever YourClass.class) instead of getClass() in above examples.
The relative path works in Java using the . specifier.
. means same folder as the currently running context.
.. means the parent folder of the currently running context.
So the question is how do you know the path where the Java is currently looking?
Do a small experiment
File directory = new File("./");
System.out.println(directory.getAbsolutePath());
Observe the output, you will come to know the current directory where Java is looking. From there, simply use the ./ specifier to locate your file.
For example if the output is
G:\JAVA8Ws\MyProject\content.
and your file is present in the folder "MyProject" simply use
File resourceFile = new File("../myFile.txt");
Hope this helps.
The following line can be used if we want to specify the relative path of the file.
File file = new File("./properties/files/ListStopWords.txt");
InputStream in = FileLoader.class.getResourceAsStream("<relative path from this class to the file to be read>");
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
String line = null;
while ((line = reader.readLine()) != null) {
System.out.println(line);
}
} catch (Exception e) {
e.printStackTrace();
}
try .\properties\files\ListStopWords.txt
I could have commented but I have less rep for that.
Samrat's answer did the job for me. It's better to see the current directory path through the following code.
File directory = new File("./");
System.out.println(directory.getAbsolutePath());
I simply used it to rectify an issue I was facing in my project. Be sure to use ./ to back to the parent directory of the current directory.
./test/conf/appProperties/keystore
While the answer provided by BalusC works for this case, it will break when the file path contains spaces because in a URL, these are being converted to %20 which is not a valid file name. If you construct the File object using a URI rather than a String, whitespaces will be handled correctly:
URL url = getClass().getResource("ListStopWords.txt");
File file = new File(url.toURI());
Assuming you want to read from resources directory in FileSystem class.
String file = "dummy.txt";
var path = Paths.get("src/com/company/fs/resources/", file);
System.out.println(path);
System.out.println(Files.readString(path));
Note: Leading . is not needed.
I wanted to parse 'command.json' inside src/main//js/Simulator.java. For that I copied json file in src folder and gave the absolute path like this :
Object obj = parser.parse(new FileReader("./src/command.json"));
For me actually the problem is the File object's class path is from <project folder path> or ./src, so use File file = new File("./src/xxx.txt"); solved my problem
For me it worked with -
String token = "";
File fileName = new File("filename.txt").getAbsoluteFile();
Scanner inFile = null;
try {
inFile = new Scanner(fileName);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
while( inFile.hasNext() )
{
String temp = inFile.next( );
token = token + temp;
}
inFile.close();
System.out.println("file contents" +token);
If text file is not being read, try using a more closer absolute path (if you wish
you could use complete absolute path,) like this:
FileInputStream fin=new FileInputStream("\\Dash\\src\\RS\\Test.txt");
assume that the absolute path is:
C:\\Folder1\\Folder2\\Dash\\src\\RS\\Test.txt
String basePath = new File("myFile.txt").getAbsolutePath();
this basepath you can use as the correct path of your file
if you want to load property file from resources folder which is available inside src folder, use this
String resourceFile = "resources/db.properties";
InputStream resourceStream = ClassLoader.getSystemClassLoader().getResourceAsStream(resourceFile);
Properties p=new Properties();
p.load(resourceStream);
System.out.println(p.getProperty("db"));
db.properties files contains key and value db=sybase
If you are trying to call getClass() from Static method or static block, the you can do the following way.
You can call getClass() on the Properties object you are loading into.
public static Properties pathProperties = null;
static {
pathProperties = new Properties();
String pathPropertiesFile = "/file.xml";
// Now go for getClass() method
InputStream paths = pathProperties.getClass().getResourceAsStream(pathPropertiesFile);
}
Im trying to write a program to read a text file through args but when i run it, it always says the file can't be found even though i placed it inside the same folder as the main.java that im running.
Does anyone know the solution to my problem or a better way of reading a text file?
Do not use relative paths in java.io.File.
It will become relative to the current working directory which is dependent on the way how you run the application which in turn is not controllable from inside your application. It will only lead to portability trouble. If you run it from inside Eclipse, the path will be relative to /path/to/eclipse/workspace/projectname. If you run it from inside command console, it will be relative to currently opened folder (even though when you run the code by absolute path!). If you run it by doubleclicking the JAR, it will be relative to the root folder of the JAR. If you run it in a webserver, it will be relative to the /path/to/webserver/binaries. Etcetera.
Always use absolute paths in java.io.File, no excuses.
For best portability and less headache with absolute paths, just place the file in a path covered by the runtime classpath (or add its path to the runtime classpath). This way you can get the file by Class#getResource() or its content by Class#getResourceAsStream(). If it's in the same folder (package) as your current class, then it's already in the classpath. To access it, just do:
public MyClass() {
URL url = getClass().getResource("filename.txt");
File file = new File(url.getPath());
InputStream input = new FileInputStream(file);
// ...
}
or
public MyClass() {
InputStream input = getClass().getResourceAsStream("filename.txt");
// ...
}
Try giving an absolute path to the filename.
Also, post the code so that we can see what exactly you're trying.
When you are opening a file with a relative file name in Java (and in general) it opens it relative to the working directory.
you can find the current working directory of your process using
String workindDir = new File(".").getAbsoultePath()
Make sure you are running your program from the correct directory (or change the file name so that it will be relative to where you are running it from).
If you're using Eclipse (or a similar IDE), the problem arises from the fact that your program is run from a few directories above where the actual source is located. Try moving your file up a level or two in the project tree.
Check out this question for more detail.
The simplest solution is to create a new file, then see where the output file is. That is the correct place to put your input file into.
If you put the file and the class working with it under same package can you use this:
Class A {
void readFile (String fileName) {
Url tmp = A.class.getResource (fileName);
// Or Url tmp = this.getClass().getResource (fileName);
File tmpFile = File (tmp);
if (tmpFile.exists())
System.out.print("I found the file.")
}
}
It will help if you read about classloaders.
say I have a text file input.txt which is located on the desktop
and input.txt has the following content
i came
i saw
i left
and below is the java code for reading that text file
public class ReadInputFromTextFile {
public static void main(String[] args) throws Exception
{
File file = new File(
"/Users/viveksingh/desktop/input.txt");
BufferedReader br
= new BufferedReader(new FileReader(file));
String st;
while ((st = br.readLine()) != null)
System.out.println(st);
}
}
output on the console:
i came
i saw
i left