I have used the Sun File Chooser Demo to choose files from my desktop or any location.
I have added the following code in the open file action:
if (returnVal == JFileChooser.APPROVE_OPTION) {
File file = fc.getSelectedFile();
log.append("Opening: " + file.getName() + "." + newline);
ReadData rd = new ReadData(); //added by me
rd.readData(file.getName()); //added by me
} else {
log.append("Open command cancelled by user." + newline);
ReadData class contains readData method which will take the file name and with BufferedReader will read the contents of the file line by line.
But after choosing the file with file chooser it is not able to open the file from my desktop.If I place the file inside the project folder it is able to open the file without any code change.
What modification in code I need to do so that it can choose and open file from any location?
Thanks
You are passing only the file's name, not the complete path, to your ReadData class. So, your ReadData class is not going to know in which directory the file is - it will try to find it in the current directory (whatever that is at the moment).
Instead of just passing the name of the file, pass the whole path:
rd.readData(file.getPath());
Better yet, change your ReadData.readData() method so that it takes a File instead of a String, and pass it the File object that you get back from the file chooser:
rd.readData(file);
getName() only gets the last segment of the file without any path information. If the working directory of your Java application isn't the exact directory that holds that file, that won't work.
Why doesn't your ReadData just take a file? All file input mechanisms built into Java will accept a File (e.g. FileInputStream, FileReader). Otherwise use getPath() I guess.
You are only passing the name of the file to the readData() method.
So if your file is stored at C:\Users\JavaBits\Project\Java\file.txt, your readData() method is only getting file.txt so it can't find the file. You should do this:
rd.readData(file);
This will have the relative path in it.
use file object to open inputstream instead using its name. such as:
BufferedReader br = new BufferedReader(new FileInputStream(file));
modify your method readData to accept File object instead String, and use this object to open BufferedReader.
Related
I have to create a temp file in the /tmp directory the code that I am using is adding random numbers to the filename. I have to use the name of the file in order to do something. With the random number, I am not able to use that file. The code I wrote is :
File dir = new File("/tmp");
String prefix = "temp";
String suffix = ".txt";
File tempFile = File.createTempFile(prefix, suffix, dir);
After using the file with the correct file name I also have to delete it how can I do that?
If you need to access the File again, you can store the path of the file to be accessed at another time.
You can get the absolute path file using:
tempFile.getAbsolutePath();
To answer your question about deleting the file after you are finished using it, you can either use the detete() or deleteOnExit() methods of File.
If your code needs a predictable filename, and you want that file to be cleaned up automatically when the program ends, don’t use a temp file (they have a random name - it’s just how they work) but rather just use deleteOnExit() with a regular file:
File file = new File("some/filename.ext");
file.deleteOnExit();
I would like to put ressources in my JAR file but, there is a problem when I want to use it. If I show the path with this code :
JOptionPane.showMessageDialog(null, MyStaticClass.class.getResource("/ressources/") + "file.File" + i, "OK", JOptionPane.INFORMATION_MESSAGE);
File file = new File(MyStaticClass.class.getResource("/ressources/") + "file.File" + i);
The result of messagebox is jar:file:/home/clement/Bureau/Untitled.jar!/ressources/niveau.Niveau1 and the exeption
java.io.FileNotFoundException: jar:file:/home/clement/Bureau/Untitled.jar!/ressources/file.File1 (No file or folder of this type)
The files are in the src folder in src/ressources/file.File1
getResourceAsStream() returns an InputStream. Your code basically tries to find file '/ressources/' which is not a file but a directory, so getResourceAsStream() returns null for it.
There is no point in printing an InputStream. What you could do is something like this:
InputStream is = MyStaticClass.class.getResourceAsStream("/ressources/" + "file.File1")
And then read its contents (for example, using InputStream's read() methods, or wrap it with an InputStreamReader and use it's read(). It's hard to give more advice as I don't know what you'd like to do with what you read.
An update for updated question code follows
getResource() returns a URL instance, which does not suit for printing as well (and for concatenating using + operator). But you can convert it to File instance if you like with help of getFile() method:
File file = new File(MyStaticClass.class.getResource("/ressources/" + "file.File" + i).getFile());
Please also note that getResource() is called on full resource name and not just directory name.
Then you could work with that File instance.
But if you just want to read the resource contents, you could do something like the following (with no need to get URL instance):
InputStream is = MyStaticClass.class.getResourceAsStream("/ressources/" + "file.File1")
Scanner scanner = new Scanner(new InputStreamReader(is, "utf-8"));
try {
if (scanner.hasNextLine()) {
System.out.println(scanner.nextLine());
}
} finally {
scanner.close();
}
This example assumes that your file is a text file and has at least one line. It prints that line to the console.
I have a text file, that I am trying to convert to a String array (where each line is an element of the array).
I have found a code here that seems to do this perfectly, the only problem is, even when I use the relative path of the file, I get a FileNotFoundException.
The relative file path:
String path = "android.resource://"+getPackageName()+"/app/src/main/res/raw/"
+ getResources().getResourceEntryName(R.raw.txtAnswers);
When I try to use this path in a reader
BufferedReader reader = null;
try{
reader = new BufferedReader(new FileReader(path));
......
The path is underlined in red and says FileNotFoundException.
Perhaps it is expecting another type of path (not relative?) or did I get the path wrong?
The relative file path
That is not a file path.
Perhaps it is expecting another type of path
res/raw/... is a file on your hard drive. It is not a file on the device.
To access raw resources, use getResources() (called on any Context, like an Activity or Service) to get a Resources object. Then, call openRawResource(), passing in your resource ID, to get an InputStream on that resource's contents.
According to me the best way would be to past that txt file in assets folder of your source code.
To use that File just use the following snippet:
InputStream inputStream = getAssets().open("YOUR_TEXT_FILE");
It returns InputStream which further can be used to read the File & convert the data into a Array
Lets say I've got a file in D: which has a filepath as:
D:\work\2012\018\08\2b558ad8-4ea4-4cb9-b645-6c9a9919ba01
at the moment the name of this file is not meaningful. It doesn't have a format. I would like to have the ability to create file object from the above filepath in Java and change its name and format before writing it into bytes. The new path could be as following:
D:\work\2012\018\08\mywork.pdf
After the changes have been made, I should still be able to gain access to the original file per normal.
I already know the type of the file and its name so there won't be a problem getting those details.
Just rename the file:
File file = new File(oldFilepath);
boolean success = file.renameTo(new File(newFilepath));
You could also just give a filename and use the same parent as your current file:
File file = new File(oldFilepath);
file.renameTo(new File(file.getParentFile(), newFilename));
It's not really clear what exactly you want; I hope this answer is useful to you.
Suppose you have a java.io.File object that represents D:\work\2012\018\08\2b558ad8-4ea4-4cb9-b645-6c9a9919ba01, and that you want to have a File object that represents D:\work\2012\018\08\mywork.pdf. You already know the new filename mywork.pdf but you want to get the directory name from the original File object. You can do that like this:
File original = new File("D:\\work\\2012\\018\\08\\2b558ad8-4ea4-4cb9-b645-6c9a9919ba01");
// Gets the File object for the directory that contains the file
File dir = original.getParentFile();
// Creates a File object for a file in the same directory with the name "mywork.pdf"
File result = new File(dir, "mywork.pdf");
The code I am running is in /Test1/Example. If I need to read a .txt file in /Test1 how do I get Java to go back 1 level in the directory tree, and then read my .txt file
I have searched/googled and have not been able to find a way to read files in a different location.
I am running a java script in an .htm file located at /Test1/Test2/testing.htm. Where it says script src=" ". What would I put in the quotations to have it read from my file located at /Test1/example.txt.
In Java you can use getParentFile() to traverse up the tree. So you started your program in /Test1/Example directory. And you want to write your new file as /Test1/Example.txt
File currentDir = new File(".");
File parentDir = currentDir.getParentFile();
File newFile = new File(parentDir,"Example.txt");;
Obviously there are multiple ways to do this.
You should be able to use the parent directory reference of "../"
You may need to do checks on the OS to determine which directory separation you should be using ['\' compared to '/']
When you create a File object in Java, you can give it a pathname. You can either use an absolute pathname or a relative one. Using absolutes to do what you want would require:
File file = new File("/Test1/myFile.txt");
if(file.canRead())
{
// read file here
}
Using relatives paths if you want to run from the location /Test1/Example:
File file = new File("../myFile.txt");
if(file.canRead())
{
// read file here
}
I had a similar experience.
My requirement is: I have a file named "sample.json" under a directory "input", I have my java file named "JsonRead.java" under a directory "testcase". So, the entire folder structure will be like untitled/splunkAutomation/src and under this I have folders input, testcase.
once after you compile your program, you can see a input file copy named "sample.json" under a folder named "out/production/yourparentfolderabovesrc/input" and class file named "JsonRead.class" under a folder named "out/production/yourparentfolderabovesrc/testcase". So, during run time, Java will actually refer these files and NOT our actual .java file under "src".
So, my JsonRead.java looked like this,
package testcase;
import java.io.*;
import org.json.simple.JSONObject;
public class JsonRead{
public static void main(String[] args){
java.net.URL fileURL=JsonRead.class.getClass().getResource("/input/sample.json");
System.out.println("fileURL: "+fileURL);
File f = new File(fileURL.toURI());
System.out.println("fileIs: "+f);
}
}
This will give you the output like,
fileURL: file:/C:/Users/asanthal/untitled/out/production/splunkAutomation/input/sample.json
fileIs: C:\Users\asanthal\untitled\out\production\splunkAutomation\input\sample.json
It worked for me. I was saving all my classes on a folder but I needed to read an input file from the parent directory of my classes folder. This did the job.
String FileName = "Example.txt";
File parentDir = new File(".."); // New file (parent file ..)
File newFile = new File(parentDir,fileName); //open the file