java create file in specific folder - java

I am trying to create a temp file in a specific folder
In the image below, you can find the structure tree of my project. I am currently in FileAnalyse.java and trying to create the file in data, under webcontent.
The following tries did not work for me:
File dir = new File(System.getProperty("user.dir")+"/WebContent/data");
File subjectFile = File.createTempFile("subjects", ".json",dir);
or
File dir = new File("/WebContent/data");
File subjectFile = File.createTempFile("subjects", ".json",dir);

File dir = new File("WebContent/data");
System.out.println(dir.getAbsolutePath()); //check the path with System.out
File subjectFile = File.createTempFile("subjects", ".json",dir);
This worked for me
note:
Your Version:
File dir = new File("/WebContent/data"); //has a / before WebContent
Correct Version:
File dir = new File("WebContent/data"); // no / before WebContent
Edit:
You can check if your path is the correct one with your attempts (or if you're on the right track to get the correct) when you print out the Path you're currently working with:
File dir = new File("YOUR/ATTEMPT");
System.out.println(dir.getAbsolutePath()); //check the path with System.out
that way you can check the absolute path, and you can look if the current attempted Pathstring is nearly correct

I solved the problem by changing the working directory of eclipse by going to run configurations->tomcat->change working directory

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()
}
}

how to get full path of the current file including the src file in java

I have a file dateTesting.java . the path's directory is as follows: D:\workspace\Project1\src\dateTesting.java . I want the full path of this file as "D:\workspace\Project1\src" itself but when I use any of the following code, i get only "D:\workspace\Project1" . the src part is not coming.
System.out.println(System.getProperty("user.dir"));
File dir2 = new File(".");
System.out.println(dir2.getCanonicalPath().toString());
System.out.println(dir2.getAbsolutePath());
How can I get the full path as "D:\workspace\Project1\src" ? I'm using eclipse ide 3.5
Thank you
dateTesting.java is a Java source file which is not available after compilation to bytecode. The source directory it was in is not available, too.
dir2 is the File of the directory you execute the .class file in. It seams that this happens to be D:\workspace\Project1 but you can't rely on this.
Your dir2 points to working directory (new File(".")). You can't get the location of your sources this way. Your file could sit inside the package (e.g. your.company.date.dateTesting). You should just manually concat the "src" to current working directory and then replace file package dots (.) with File.pathSeparator. In that way you will build the full path to your file.
String fullFilePath = "H:\\Shared\\Testing\\abcd.bmp";
File file = new File(fullFilePath);
String filePath = file.getAbsolutePath().substring(0,fullFilePath.lastIndexOf(File.separator));
System.out.println(filePath);
Output:
H:\Shared\Testing
If you are doing this to try to read a file from the classpath, then check out this answer:
How to really read text file from classpath in Java
Essentially you can do this
InputStream in = this.getClass().getClassLoader()
.getResourceAsStream("SomeTextFile.txt");
Otherwise, if you have some other requirement, one option is to pass through the src directory as a JVM arg when the application begins and then just read it back.
/** The actual file running */
public static final File JAR_FILE = new File(MyClass.class.getProtectionDomain().getCodeSource().getLocation().getPath();
/** The path to the main folder where the file .jar is run */
public static final String BASE_DIRECTORY = (JAR_FILE != null ? JAR_FILE.getAbsolutePath().replace(JAR_FILE.getName(), "") : "notFound");
This will work for you both in normal java execution and jar execution. This is the solution I am using in my project.

How to open file in another directory in java?

How to open a file that is not present in the current directory but in another directory. For example, I have a folder F:/test and my file is in F:/test/test2/doit.txt and D:/test3/doit2.txt
What to enter in path in parameter while making File object as follows :
File f = new File("/test2/doit.txt");
Irrespective of which operating system, a file for example, demo.txt can be accessed like
File file = new File("/d:/user/demo.txt");
in Windows where the file is at D:\user\ and
File file = new File("/usr/demo.txt");
in *nix or *nuxwhere the file is at /usr/
Also, a file if wanted to be accessed relatively can be done as (considering the Windows example) :
Suppose I am in the songs directory in D: like:
D:/
|
|---songs/
| |
| |---Main.java
|
|---user/
|
|---demo.txt
and the code is inside Main.java, then the following code works.
File file = new File("../user/demo.txt");
Assuming that you are running your program from F:/test you should use something like:
File f = new File("./test2/doit.txt");
Using hardcoded absolute paths isn't a good idea - your program might not work when user has different directory structure.
File inside of a project can be open as:
File file = new File(path);
or
File file = new File(./path);
where path is relative path from the project.
For example, when the project name is test and the file with name fileName is inside the test project:
File file = new File("fileName");
or
File file = new File("./fileName");
Please try the code below on Windows OS:
reader = new FileReader ("C:/Users/user/Desktop/java/test.txt");

java: How to copy a directory in a jar file to a tmp dir?

I know how to create a temporary directory in Java, but is there an easy way to copy files in Java from the jar file to this directory?
File tmpDir = new File(System.getProperty("java.io.tmpdir"));
File helpDir = new File(tmpDir, "myApp-help");
helpDir.createNewFile(); // oops, this isn't right, I want to create a dir
URL helpURL = getClass().getResource("/help-info");
/* ???? I want to copy the files from helpURL to helpDir */
Desktop desktop = Desktop.getDesktop();
URI helpURI = /* some URI from the new dir's index.html */
desktop.browse(helpURI);
Apache's org.apache.commons.io.FileUtils can do that for you
To create directory use File.mkdir();
Convert URL to File with org.apache.commons.io.FileUtils.toFile(URL)
use org.apache.commons.io.FileUtils.copyFile() to copy.
You can make use of the command jar tf [here your jarfile]. This will list the contents of the JAR Archive with their full path, relative to the jarfile (1 line = 1 file). Check if the line starts with the path of the directory you want to extract, and use Class.getResourceAsStream(URL) for the matching lines and extract them to your temporary folder.
Here is an example output of jar tf:
META-INF/MANIFEST.MF
TicTacToe.class
audio/
audio/beep.au
audio/ding.au
audio/return.au
audio/yahoo1.au
audio/yahoo2.au
images/
images/cross.gif
images/not.gif

Find Path During Runtime To Delete File

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.

Categories