Find Path During Runtime To Delete File - java

The code basically allows the user to input the name of the file that they would like to delete which is held in the variable 'catName' and then the following code is executed to try and find the path of the file and delete it. However, it doesn't seem to work, as it won't delete the file this way. Is does however delete the file if I input the whole path.
File file = new File(catName + ".txt");
String path = file.getCanonicalPath();
File filePath = new File(path);
filePath.delete();

If you're deleting files in the same directory that the program is executing in, you don't need specify a path, but if it's not in the same directory that your program is running in and you're expecting the program to know what directory your file is in, that's not going to happen.
Regarding your code above: the following examples all do the same thing. Let's assume your path is /home/kim/files and that's where you executed the program.
// deletes /home/kim/files/somefile.txt
boolean result = new File("somefile.txt").delete();
// deletes /home/kim/files/somefile.txt
File f = new File("somefile.txt");
boolean result = new File(f.getCanonicalPath()).delete();
// deletes /home/kim/files/somefile.txt
String execPath = System.getProperty("user.dir");
File f = new File(execPath+"/somefile.txt");
f.delete();
In other words, you'll need to specify the path where the deletable files are located. If they are located in different and changing locations, then you'll have to implement a search of your filesystem for the file, which could take a long time if it's a big filesystem. Here's an article on how to implement that.

Depending on what file you want to delete, and where it is stored, chances are that you are expecting Java to magically find the file.
String catName = 'test'
File file = new File(catName + '.txt');
If the program is running in say C:\TestProg\, then the File object is pointing to a file in the location C:\TestProg\test.txt. Since the file object is more of just a helper, it has no issues with pointing to a non-existent file (File can be used to create new files).
If you are trying to delete a file that is in a specific location, then you need to prepend the folder name to the file path, either canonically, or relative to the execution location.
String catName = 'test'
File file = new File('myfiles\\'+ catName +'.txt');
Now file is looking in C:\TestProg\myfiles\test.txt.
If you want to find that file anywhere, then you need a recursive search algorithm, that will traverse the filesystem.

The piece of code that you provided could be compacted to this:
boolean success = new File(catName + ".txt").delete();
The success variable will be true if the deletion was successful. If you do not provide the full absolute path (e.g. C:\Temp\test for the C:\Temp\test.txt file), your program will assume that the path is relative to its current working directory - typically the directory from where it was launched.
You should either provide an absolute path, or a path relative to the current directory. Your program will not try to find the file to delete anywhere else.

Related

Gradle project and resources folder and logical root for creating files

I have a problem understanding how Intellij is working with a Gradle project and the resources folder.
I have created a default Gradle project its created a module 'group', and a module when looking in the module group the src/main/resources folder shows as a 'resource folder' (however it doesn't in the stand-alone module, where groovy/java/resources are all grey).
So that sort out seems to work when compiling code generally.
I tried however to create a file in Groovy script like this
File newFile = new File ("resources/temp.txt")
def fpath = newFile.toURL()
if (!newFile.exists()) {
println "creating new $fpath file "
newFile.createNewFile()
}
However run you run this it fails at bit like this
creating new file:/D:/Intellij - Azure/quickstart-java/graph/src/main/groovy/playpen/resources/temp.txt file
Caught: java.io.IOException: The system cannot find the path specified
java.io.IOException: The system cannot find the path specified
at java_io_File$createNewFile$1.call(Unknown Source)
at playpen.TinkerPop-Example.run(TinkerPop-Example.groovy:47)
The File seems to have relative root .../src/main/groovy/playpen which is where my script is. there is no src/main/groovy/playpen/resources/ so it fails
if a use File("/resources/temp.txt") and look at the URL it shows asD:\resources\temp.txt` defaulting to same drive as where the script is defined.
If you remove the resources prefix - the file gets created in playpen - again assumed root is same as the source program script.
What I want is to read a file from the 'resources' folder but unless I go to absolute file paths it just ignores the 'resources' folder and only looks in the Groovy source folders.
So for example if I copy the temp.txt into the resources folder and run this
File newFile = new File ("temp.txt")
def fpath = newFile.toURL()
if (!newFile.exists()) {
println "creating new $fpath file "
newFile.createNewFile()
} else {
println "reading file at $fpath"
}
it just creates a new temp.txt in the playpen package where the script runs and doesn't see a copy from 'resources' folder.
So what format of 'file name' do I use so that the 'resources' folder is naturally used to resolve file names - without having to use absolute file names?
Equally if want to create a File programmatically and save that in the 'resources' folder where the script runs from src/main/groovy/playpen, what's the path name that puts it in the correct location.
I'm missing something basic here and can't figure out how to read/or write from the resources folder.
ended up with brute force and ignorance on this one - someone may have a 'smarter'answer, but this one appears to be working. Slightly tweaked some code i got working.
I'm using groovy here rather than java (just less boilerplate noise), and nice File groovy methods
steps -
(1)first locate root of your IDE/project using System.getProperty("user.dir")
(2) get the current resource file for 'this' - the class you run from ide
(3) see if the resource is in $root/out/test/.. dir - it so its a test else its your normal code.
(4) set resourcePath now to correct 'location' either in src/main/resources or src/test/resources/ - then build rest of file from this stub
(5) check if file exists - if so delete and rewrite this (you can make this cleverer)
(6) create file and fill its contents
job done this file should now appear where you expect it. Happy to take cleverer ways to get do this - but for anyone else stuck this seems to do the trick
void exportToFile (dir=null, fileName=null) {
boolean isTest = false
String root = System.getProperty("user.dir")
URL url = this.getClass().getResource("/")
File loc = new File(url.toURI())
String canPath = loc.getCanonicalPath()
String stem = "$root${File.separatorChar}out${File.separatorChar}test"
if (canPath.contains(stem))
isTest = true
String resourcesPath
if (isTest)
resourcesPath = "$root${File.separatorChar}src${File.separatorChar}test${File.separatorChar}resources"
else
resourcesPath = "$root${File.separatorChar}src${File.separatorChar}main${File.separatorChar}resources"
String procDir = dir ?: "some-dir-string"
if (procDir.endsWith("$File.separatorChar"))
procDir = procDir - "$File.separatorChar"
String procFileName = fileName ?: "somedefaultname"
String completeFileName
File exportFile = "$resourcesPath${File.separatorChar}$procDir${File.separatorChar}${procFileName}"
exportFile = new File(completeFileName)
println "path: $procDir, file:$procFileName, full: $completeFileName"
exportFile.with {
if (exists())
delete()
createNewFile()
text = toString()
}
}

FileAlreadyExistsException when using Files.copy

I am trying to copy a file from an InputStream into a local directory. I created a local directory called test, and it is located in my package root.
public void copyFileFromInputStream(InputStream is) {
Path to = Paths.get("test");
Files.copy(is, to);
}
Clearly I am misunderstanding Files.copy(...), because it seems like it is trying to create a new file called "test" instead of placing the file into the directory "test".
How do I write the file into the directory?
First create the new directory, then copy the stream to a new file in that directory:
Path to = Paths.get("mynewdir/test");
Files.copy(is, to);
Also bare in mind that your InputStream does not have a filename, so you will always need to provide a filename when writing the stream to disk. In your example, it will indeed try to create a file 'test', but apparently that is a folder that already exists (hence the Exception). So you need to specify the full filename.
Here is a answer for you question:
Referring to you code snippet: Paths.get("test");
you're asking a file path to the file named "test" in the current directory but not the directory.
If you want to refer the file under test directory which in tern under your current directory. use the following:
Paths.get("test/filename.ext") to which you want to write your stream data.
If you run your app twice, you get "FileAlreadyExistsException" because copy method on Files writes to new file , if exists it'll not override it.
I hope this helps you!
The 'to' parameter of Files.copy(from, to) is the path to the destination file.
Try specifying what file name inside the test directory:
Path to = Paths.get("test/newfilename");
Files.copy(is, to);
You can use the option StandardCopyOption.REPLACE_EXISTING :
public void copyFileFromInputStream(InputStream is) {
Path to = Paths.get("test");
Files.copy(is, to, StandardCopyOption.REPLACE_EXISTING);
}

Save a binary file in the same folder for every PC

I'm making a game that saves information into a binary file so that I can start at the point I left the game on the next use.
My problem is that it works fine on my PC because I chose a path that already existed to save the file, but once I run the game on another PC, I got an error saying the path of the file is invalid (because i doesn't exist yet, obviously).
Basically I'm using the File class to create the file and then the ObjectOutputStream and ObjectInputStream to read/write info.
Sorry for the noob question, I'm still pretty new to using files.
You must first check if the directory exists and if it does not exist then you must create it.
String folderPath = System.getProperty("user.home") + System.getProperty("file.separator") + "MyFolder";
File folder = new File(folderPath);
if(!folder.exists())
{
folder.mkdirs();
}
File saveFile = new File(folderPath, "fileName.ext");
Please note that the mkdirs() method is more useful in this case instead of the mkdir() method as it will create all non existing parent folders.
Hope this helps. Good luck and have fun programming!
Cheers,
Lofty
You are looking for File mkdirs()
Which will create all the directories necessary that are named in your path.
For example:
File dirs= new File("/this/path/does/not/exist/yet");
dirs.mkdir();
File file = new File(dirs, "myFile.txt");
Take in consideration that it may fail, due to proper file permissions.
My solution has been create a subdirectory within the user's home directory (System.getProperty("user.home")), like
File f = new File(System.getProperty("user.home") + "/CtrlAltDelData");
f.mkdir();
File mySaveFile = new File (f, "save1.txt");

Specifying a relative path in File in Java

I'm uploading images using Spring and Hibernate. I'm saving images on the server as follows.
File savedFile = new File("E:/Project/SpringHibernet/MultiplexTicketBooking/web/images/" + itemName);
item.write(savedFile);
Where itemName is the image file name after parsing the request (enctype="multipart/form-data"). I however need to mention the relative path in the constructor of File. Something like the one shown below.
File savedFile = new File("MultiplexTicketBooking/web/images/" + itemName);
item.write(savedFile);
But it doesn't work throwing the FileNotFoundException. Is there a way to specify a relative path with File in Java?
Try printing the working directory from your program.
String curDir = System.getProperty("user.dir");
Gets you that directory. Then check if the directories MultiplexTicketBooking/web/images/ exist in that directory.
Can't count the number of times I've been mistaken about my current dir and spent some time looking for a file I wrote to...
It seems the server should offer functionality as might be seen in the methods getContextPath() or getRealPath(String). It would be common to build paths based on those types of server related and reproducible paths. Do not use something like user.dir which makes almost no sense in a server.
Update
ServletContext sc=request.getSession().getServletContext();
File savedFile = new File(sc.getRealPath("images")+"\\" + itemName);
Rather than use "\\" I'd tend to replace that with the following which will cause the correct file separator to be used for each platform. Retain cross-platform compatibility for when the client decides to swap the MS/ISS based server out for a Linux/Tomcat stack. ;)
File savedFile = new File(sc.getRealPath("images"), itemName); //note the ','
See File(String,String) for details.
You could get the path of your project using the following -
File file = new File("");
System.out.println("" + file.getAbsolutePath());
So you could have a constants or a properties file where you could define your path which is MultiplexTicketBooking/web/images/ after the relative path.
You could append your path with the path you get from file.getAbsolutePath() and that will be the real path of the file. - file.getAbsolutePath() + MultiplexTicketBooking/web/images/.
Make sure the folders after the Project path i.e. MultiplexTicketBooking/web/images/ exist.
You can specify the path both absolute and relative with File. The FileNotFoundException can be thrown because the folder might be there. Try using the mkdirs() method first in to create the folder structure you need in order to save your file where you're trying to save it.

Getting error saying file won't open in Java...any idea why this is happening?

I think I am really close, but I am unable to open a file I have called LocalNews.txt. Error says can't find file specified.
String y = "LocalNews.txt";
FileInputStream fstream = new FileInputStream(y);
DataInputStream in = new DataInputStream(fstream);
BufferedReader br = new BufferedReader(new InputStreamReader(in));
Name of file is LocalNews.txt in library called News....anyone know why the file will not open?
The file is in the same Java Project that I am working on.
Error: LocalNews.txt (The system cannot find the file specified)
Project is named Bst, package is src in subPackage newsFinder, and library that the text files are stored in is called News.
Found out it was looking in
C:\EclipseIndigoWorkspace1\Bst\bin\LocalNews.txt
But I want it to look in (I believe)
C:\EclipseIndigoWorkspace1\Bst\News\LocalNews.txt
But if I make the above url a string, I get an error.
String y = "LocalNews.txt";
instead use
String y = "path from root/LocalNews.txt"; //I mean the complete path of the file
Your program can probably not find the file because it is looking in another folder.
Try using a absolute path like
String y = "c:\\temp\\LocalNews.txt";
By 'library called News' I assume you mean a jar file like News.jar which is on the classpath and contains the LocalNews.txt file you need. If this is the case, then you can get an InputStream for it by calling:
InputStream is = Thread.currentThread().getContextClassLoader()
.getResourceAsStream("LocalNews.txt");
Use
System.out.println(System.getProperty("user.dir") );
to find out what your current directory is. Then you'll know for sure whether your file is in the current directory or not. If it is not, then you have to specify the path so that it looks in the right directory.
Also, try this -
File file = new File (y);
System.out.println(file.getCanonicalPath());
This will tell you the exact path of your file on the system, provided your file is in the current directory. If it does not, then you know your file is not in the current directory.

Categories