How to change file path location in java.io.File object [duplicate] - java

This question already has answers here:
What is meant by immutable?
(17 answers)
Closed 3 years ago.
The question says it all.
I have a File object which is pointing to /home/user/filename1.
If I call file.getAbsolutePath() then it would return /home/user/filename1
My question is that -
Can we change the path inside file object to a different location?
If yes, then how?
Thanks

"Instances of the File class are immutable; that is, once created, the abstract pathname represented by a File object will never change. "
From the File javadoc.

I had developed a code to rename the file and I have to save the file in the same location recursively. I think the below code helps you out upto some extent. I have to replace "-a" in my filename and save it in the same folder. If needed in place of "destPath" you can give the destination path of your string path. I think this might help you.
File oldfile =new File(file.getAbsolutePath());
String origPath = file.getCanonicalPath();
String destPath = origPath.replace(file.getName(),"");
String destFile = file.getName();
String n_destFile = destFile.replace("-a", "");
File newfile =new File(destPath+n_destFile);

A file is internally nothing else other then a string holding the path to the file. So no this is not possible. Why would you even want to do something like this? Unless you have moved the file to another location?

As someone noted before, File is immutable as many of java API classes. Maybe what you want is to copy a file from somewhere to some other place? Have in mind that a File object has no actual binding to the contents of the file, and will not allow you modifying or moving it.
Have a look at Apache Commons IO
http://commons.apache.org/proper/commons-io/apidocs/org/apache/commons/io/IOUtils.html
Here you have a useful library to deal with files.

Related

Java: Referencing a file after being packaged (jar), getResourceAsStream? [duplicate]

This question already has an answer here:
Any way to get a File object from a JAR
(1 answer)
Closed 5 years ago.
I'm trying to implement a button into my project which, when clicked, automatically loads a specific file. Currently there are buttons for users selecting a file from their hard disk.
So, I downloaded the specific file and inserted it into the project. When using File f = new File("demofile") or something like this
getClass().getResource("/resources/file.txt").getFile(); the code WORKS locally.
However, when the project is packaged, a FileNotFoundException is thrown.
After much research online, there are suggestions to use something like:
InputStream is = getClass().getResourceAsStream("/resources/file.txt");
However, for this project, I need the file to be referenced as a file object so that it can be passed as an argument to other functions, such as:
in = new TextFileFeaturedSequenceReader(TextFileFeaturedSequenceReader.FASTA_FORMAT, file, DiffEditFeaturedSequence.class);
Any ideas on how I can solve this, or read a stream into a file object?
Thanks!
If you absolutely must pass a File, copy your resource to a temporary file:
Path path = Files.createTempFile(null, null);
try (InputStream stream =
getClass().getResourceAsStream("/resources/file.txt")) {
Files.copy(stream, path, StandardCopyOption.REPLACE_EXISTING);
}
in = new TextFileFeaturedSequenceReader(
TextFileFeaturedSequenceReader.FASTA_FORMAT,
path.toFile(),
DiffEditFeaturedSequence.class);
// Use the TextFileFeaturedSequenceReader as needed
// ...
Files.delete(path);

Files searching in Java

Because I asked wrong question last time, I want to correct my intention. How can I find file by name in specified folder? I have a variable with a name of this file and i want to find it in specified folder. Any ideas?
Maybe the simplest thing that works is:
String dirPath = "path/to/directory";
String fileName = "foo.txt";
boolean fileExistsInDir = new File( dirPath, fileName ).exists();
File is just a placeholder for a location in the file system. The location does not have to exist.
Use Finding files in Java as a starting point. It should have everything that you are looking for - ask another specific question if you get stuck.

Make a path for create a file in Java (Android)

Given a File object how can I create the path for saving it?
I tried file.mkdirs() but for example if the file's path is:
/mnt/sdcard/downloads/myapp/temp/song.mp3
it also creates a folder named "song.mp3" inside temp.
How can I do it correctly?
use this code
File myDir=new File("/sdcard/Download");
myDir.mkdirs();
String fname = "Image.jpg";
File file = new File (myDir,fname);
Just try:
file.getParentFile().mkdirs();
this will create the parent directory.
If I have understand correctly what you need is
File.getParent()
hope it helps
If you just want to extract the path you can use lastIndexOf:
String p = "/mnt/sdcard/downloads/myapp/temp/song.mp3";
System.out.println(p.substring(0,p.lastIndexOf('/')));
Of course, if you already have File object then getParent(), as suggested, will be easier.

Programmatically reading static resources from my java webapp [duplicate]

This question already has answers here:
How to find the working folder of a servlet based application in order to load resources
(3 answers)
Closed 6 years ago.
I currently have a bunch of images in my .war file like this.
WAR-ROOT
-WEB-INF
-IMAGES
-image1.jpg
-image2.jpg
-index.html
When I generate html via my servlets/jsp/etc I can simple link to
http://host/contextroot/IMAGES/image1.jpg
and
http://host/contextroot/IMAGES/image1.jpg
Not I am writing a servlet that needs to get a filesystem reference to these images (to render out a composite .pdf file in this case). Does anybody have a suggestion for how to get a filesystem reference to files placed in the war similar to how this is?
Is it perhaps a url I grab on servlet initialization? I could obviously have a properties file that explicitly points to the installed directory but I would like to avoid additional configs.
If you can guarantee that the WAR is expanded, then you can use ServletContext#getRealPath() to convert a relative web path to an absolute disk file system which you can further use in the usual Java IO stuff.
String relativeWebPath = "/IMAGES/image1.jpg";
String absoluteDiskPath = getServletContext().getRealPath(relativeWebPath);
File file = new File(absoluteDiskPath);
InputStream input = new FileInputStream(file);
// ...
However, if you can't guarantee that the WAR is expanded (i.e. all resources are still packaged inside WAR) and you're actually not interested on the absolute disk file system path and all you actually need is just an InputStream out of it, then use getServletContext().getResourceAsStream() instead.
String relativeWebPath = "/IMAGES/image1.jpg";
InputStream input = getServletContext().getResourceAsStream(relativeWebPath);
// ...
See also:
getResourceAsStream() vs FileInputStream
Use the getRealPath method of ServletContext.
Ex:
String path = getServletContext().getRealPath("WEB-INF/static/img/myfile.jpeg");
This is relatively straight forward you simply use the class loader to fetch the files from the class plath. :
InputStream is = YourServlet.class.getClassLoader().getResourceAsStream("IMAGES/img1.jpg");
There are a few other getResoruce classes that are worth looking at. Also you don't have to fetch the class loader through the class variable on your servlet. Any class that you happen to know has been loaded by the container should work .
If you know the relative location of the files you could ask the runtime about the exact location using
Thread.currentThread().getContextClassLoader().getResource(<relative-path>/<filename>)
This would give you an URL to the location where the specified image can be found. This URL can be used to read the specified file or you can split it to use the different parts of the URL for further processing.

Check if a text file exists

I need to pick a text file from a folder and read the data in the file. The file is generated dynamically in that folder in the format "XXX_2010-12-06". So, first i need to check if the file is existing in the folder and if it exists the content of the file should be read.
I have the code to read the content in the text file. I need to provide the path of the file
Can anyone help me in coding this using java...
You can create a new instance of File and initiate it with the path to the file itself.
File file = new File("/a/path/to/a/file/TheFile.txt");
Once you have your File instance created you can check to see if it exists by calling the exists() method inside of File.
System.out.println(file.exists() ? "The file exists!" : "The file doesn't exist!");
I couldn't really understand what you were asking for help with. But if you edit your question to be more clear I will edit my answer to fulfill further answering.
The File class has methods for checking whether a file exists.

Categories

Resources