linux - cannot view directory created from java - java

I am using the following piece of code to create a directory in java, under Linux:
String dir = "~/tempDir/";
if (!IOUtils.createDirectory(dir)) {
throw new IOException("could no create the local store directory: "
+ dir );
}
LOGGER.info("local store successfully created.");
The application seems to create the directory, as I get no errors and it is working fine.
The problem is that I cannot see this directory on the disk; I am looking in my home directory.
I need to mention that this is a java web application running under tomcat.
Does anyone have any idea why I cannot see this directory?

This does not work because ~ is expanded by your shell, bash or sh or whatever. This doesn't work from Java.
You have created a directory called ~ in your working directory.
You need to get the user's home directory from the system property user.home and build your path from that.
final File dir = new File(System.getProperty("user.home"), "tempDir");

The following will create a "New Folder" under Home, if a folder with the specified name does NOT exist already
final String homePath = System.getProperty("user.home") + "/";
final String folderName = "New Folder";
File file = new File(homePath + folderName);
if (!file.exists())
file.mkdir();
Another option (a better one I should say) you have is using another constructor of File that takes a parent path and a child path as follows:
final String homePath = System.getProperty("user.home");
final String folderName = "New Folder";
File file = new File(homePath, folderName);
if (!file.exists())
file.mkdir();

Related

How to get %HOMEPATH% of file system from java

Is there a way to get user's home directory from java code?
For example: my user's home directory absolute path is C:\Users\stanislav. If I type %HOMEPATH% in Windows file explorer it will open me my user's directory.
I want to get this directory as File from JAVA using this code:
final Path homePath = Path.of("%HOMEPATH%");
final File file = homePath.toFile();
file.exists() // returns false
But this path is not referred to any file or directory. Help please.
String usersHomeDir = System.getProperty("user.home");
You can do
System.getProperty("user.home");
to get the home directory for the current user as a String. You can then pass the result to the File constructor to create a File object.
String home = System.getProperty("user.home");
System.out.println(home); // prints the path to your home directory
File file = new File(home);
System.out.println(file.exists()); // prints true

Packaged Jar unable to read files from mapped network drive (Windows)

I have a Spring Boot application which reads files in folders on a mapped network drive, i.e. m:/PRODUCTION
The problem is, when I execute the jar file, my debugging output shows that no files exist in the folder, even though the folder is full of a files.
I have IntelliJ installed on the same machine, and if I run the application from it's source code, it works absolutely fine.
The method I have that reads filename to an array is;
private File[] getFilesInPath(String path) {
File folder = new File(path);
File[] listOfFiles = folder.listFiles();
if (listOfFiles != null) {
Arrays.sort(listOfFiles, Comparator.comparingLong(File::lastModified));
}
return listOfFiles;
}
Then, I call this function from a number of places in the application, here's an example;
public void manuallyProcessAttritionData(List<Line> lines) {
Handler handler = new AttritionHandler().setLines(lines).setService(this);
String pathToProcess = dataFolder + attritionFolder;
log.debug("Processing path: " + pathToProcess);
File[] listOfFiles = getFilesInPath(pathToProcess);
if (listOfFiles != null) {
log.debug("Number of files to process: " + listOfFiles.length);
for (File file : listOfFiles) {
handler.processFile(file);
}
} else {
log.debug("No files to process");
}
}
The output from running the above is;
Processing ATTRITION data...
Processing path: m:/PRODUCTION
No files to process
...Finished processing ATTRITION data
I've confirmed the path is correct, running the following commands from the command line works fine and there are files in the result;
cd m:\PRODUCTION
M:\PRODUCTION>
Does anyone know of a reason why the folder can be read perfectly find from the application running in IntelliJ, but not when packaged as a JAR file?
Looks like your development account Intellij has access to this drive where as the account which started this spring-boot doesn't have access to it.
I would suggest using full path instead of a mapped network path.
There should be no difference in running the code from intelliJ or running it from the built jar. But there may be other factors comming into play. Maybe you run intelliJ with a different user than the jvm that runs the jar? I propose the following steps to resolve the issue:
1. Use the Path Class to avoid platform specific problems (eg. file separators)
Instead of
new File("path/to/my/directory");
you should use
Paths.get("path", "to", "my", "directory").toFile()
or
Paths.get("path/to/my/directory").toFile()
2. Check the file attributes
Use the code below to investigate if the directory exists, if you have the correct permissions etc.
Path directory = Paths.get("e:/TEMP");
System.out.println("Absolute Path of directory: " + directory.toAbsolutePath());
System.out.println("Directory exists: " + directory.toFile().exists());
System.out.println("Directory is a directory: " + directory.toFile().isDirectory());
System.out.println("Directory isReadable: " + directory.toFile().canRead());
System.out.println("Directory isWriteable: " + directory.toFile().canWrite());
this should output something like:
Absolute Path of directory: e:\TEMP
Directory exists: true
Directory is a directory: true
Directory isReadable: true
Directory isWriteable: true

Absolute Path from File in Package

Let's say I have a package: com.example.resources and inside it I have picture.jpg and text.txt - How can I use only the package path to identify the absolute filepath of picture.jpg and text.txt?
Is this correct?
File file1 = new File("/com/example/resources/picture.jpg");
file1.getAbsolutePath();
File file2 = new File("/com/example/resources/text.txt");
file2.getAbsolutePath();
"I'm trying to reference those files within the application so that when I deploy the application to different systems I won't have to reconfigure the location of each resource "
You don't want to use a File, which will load from the file system of the local machine, you want to load through the class path, as that's how embedded resources should be read. Use getClass().getResourceAsStream(..) for the text file and getClass().getReource(..) for the image
Your current path you're referencing looks like it should work, given the package name you've provided.
Take a look at this answer and this answer as some references.
I've figured out how to do it. Here is the code that I used:
public String packagePathToAbsolutePath(String packageName, String filename) {
String absolutePath = "File not found";
URL root = Thread.currentThread().getContextClassLoader().getResource(packageName.replace(".", "/"));
File[] files = new File(root.getFile()).listFiles();
for (File file : files) {
if (file.getName().equals(filename)) {
absolutePath = file.getName();
return absolutePath;
}
}
return absolutePath;
}
This method was really useful because it allowed me to configure the resource paths within the application so that when I ran the application on different systems I didn't have to reconfigure any paths.

How to set file path to src folder of project

I want to make a program that you can email to someone and they can run it.
Right now my code for making a file is like this:
File f = new File("/Users/S0urceC0ded/Desktop/Code/project/JavaStuffs/src/axmlfile.xml);
f.createNewFile();
But what if someones username is not S0urceC0ded, or they put the project in a different place? How could I set the file path to the src folder plus the filename?
Leave the path off entirely, it will use the directory of the project.
Change
File f = new File("/Users/S0urceC0ded/Desktop/Code/project/JavaStuffs/src/axmlfile.xml");
To
File f = new File("axmlfile.xml");
I generally use code like this for temporary file storage, this way it gets cleaned up when the application finishes. If required you can allow the user to save a version of the file or move it to a permanent location.
try{
//create a temporary file
File temp = File.createTempFile("axmlfile", ".xml");
System.out.println("Location: " + temp.getAbsolutePath());
}catch(IOException e){
e.printStackTrace();
}

Getting the directory name in java

How do I get the directory name for a particular java.io.File on the drive in Java?
For example I have a file called test.java under a directory on my D drive.
I want to return the directory name for this file.
File file = new File("d:/test/test.java");
File parentDir = file.getParentFile(); // to get the parent dir
String parentDirName = file.getParent(); // to get the parent dir name
Remember, java.io.File represents directories as well as files.
With Java 7 there is yet another way of doing this:
Path path = Paths.get("d:/test/test.java");
Path parent = path.getParent();
//getFileName() returns file name for
//files and dir name for directories
String parentDirName = path.getFileName().toString();
I (slightly) prefer this way, because one is manipulating path rather than files, which imho better shows the intentions. You can read about the differences between File and Path in the Legacy File I/O Code tutorial
Note also that if you create a file this way (supposing "d:/test/" is current working directory):
File file = new File("test.java");
You might be surprised, that both getParentFile() and getParent() return null. Use these to get parent directory no matter how the File was created:
File parentDir = file.getAbsoluteFile().getParentFile();
String parentDirName = file.getAbsoluteFile().getParent();
File file = new File("d:/test/test.java");
String dirName = file.getParentFile().getName();
Say that you have a file called test.java in C:\\myfolder directory. Using the below code, you can find the directory where that file sits.
String fileDirectory = new File("C:\\myfolder\\test.java").getAbsolutePath();
fileDirectory = fileDirectory.substring(0,fileDirectory.lastIndexOf("\\"));
This code will give the output as C:\\myfolder

Categories

Resources