Create directory/directories in Eclipse with java.io.File - java

I tried to make it as easy as possible.
Example:
File f = new File("non_existing_dir/someDir");
System.out.println(f.mkdir());
System.out.println(f.mkdirs());
mkdir() and mkdirs() return both false °_°. Both work (create directory) if i use double backslash \\ (like "\\non_existing_dir\\someDir" BUT:
if I do .toURI() after that I receive: file:/Users/MyName/Desktop/%5Cnon_existing_dir%5CsomeDir/
if I do .getPath() i receive: \non_existing_dir\someDir
if I do .getCanonicalPath() I receive: /Users/MyName/Desktop/\non_existing_dir\someDir
So i want to have instead this results:
with .toURI() receiving: file:/Users/MyName/Desktop/non_existing_dir/someDir/
with .getPath() receiving: /non_existing_dir/someDir
and with .getCanonicalPath() receiving: /Users/MyName/Desktop/non_existing_dir/someDir
Thanks in advance to everyone.

If non_existing_dir does not exists, you can check getParentFile() and create it with mkdir().
Also avoid problems between OS with File.separator.
String filename = "non_existing_dir" + File.separator + "someDir";
File f = new File(filename);
if (!f.exists()) {
if (!f.getParentFile().exists()) {
// make the dir
f.getParentFile().mkdir();
}
f.mkdir();
}

Related

Test works on local Windows machine but fails on Linux server

I have this test:
#Test
void testHeader() {
String inputFile = ".\\src\\main\\resources\\binaryFile";
MDHeader addHeader = new MDHeader();
try (
InputStream inputStream = new FileInputStream(inputFile);
) {
long fileSize = new File(inputFile).length();
byte[] allBytes = new byte[(int) fileSize];
inputStream.read(allBytes);
ProducerRecord<String, byte[]> record = new ProducerRecord<String, byte[]>("foo", allBytes);
ProducerRecord<String, byte[]> hdr = addHeader.addMDHeader(record);
for (Header header : hdr.headers()) {
assertEquals("mdpHeader", header.key());
}
}
catch(Exception e) {
assert (false);
}
}
The test succeeds when run locally through Eclipse on my Windows desktop but it fails at com.me.be.HeaderTests.testMDHeader(HeaderTests.java:81) when trying to build the jar on a Linux server. That's the line assert (false). I haven't got any more information on the issue yet but was wondering if it could be the backslashes in inputFile in a Linux environment?
Java on Windows and Linux will both accept / as path separator, whereas Linux does not like \\ as a path separator - so treats the whole string as ONE path component, not 4 parts as you'd expect:
String inputFile = "./src/main/resources/binaryFile";
However for file handling it is better to use java.nio.Path or java.io.File in place of String.
WINDOWS
jshell> Path.of("./src/main/resources/binaryFile")
$2 ==> .\src\main\resources\binaryFile
Linux
jshell> Path.of("./src/main/resources/binaryFile")
$1 ==> ./src/main/resources/binaryFile
You can also use Path.of without any file separator for any OS:
Path p = Path.of("src","main","resources","binaryFile");
The File.separator string is handy to concat into the path string in order to produce an OS independent file path.
String inputFile = "." + File.separator + "src" + File.separator + "main" + File.separator + "resources" + File.separator + "binaryFile";
Should give you a cross platform compliant file path.

Creating file on filesystem with java.io.File

I'm trying to create an empty .properties file on my filesystem using java.io.File.
My code is:
File newFile = new File(new File(".").getAbsolutePath() + "folder\\" + newFileName.getText() + ".properties");
if (newFile.createNewFile()){
//do sth...
}
It says that it's impossible to find the specified path.
Printing the Files's constructor's argument it shows correctly the absolute path.
What's wrong?
You can use new File("folder", newFileName.getText() + ".properties") which will create a file reference to the specified file in the folder directory relative to the current working directory
You should make sure that the directory exists before calling createNewFile, as it won't do this for you
For example...
File newFile = new File("folder", newFileName.getText() + ".properties");
File parentFile = newFile.getParentFile();
if (parentFile.exists() || parentFile.mkdirs()) {
if (!newFile.exists()) {
if (newFile.createNewFile()){
//do sth...
} else {
throw new IOException("Could not create " + newFile + ", you may not have write permissions or the file is opened by another process");
}
}
} else {
throw new IOException("Could not create directory " + parentFile + ", you may not have write permissions");
}
I think the "." operator might be causing the error not sure what you are trying to do there, may have misunderstood your intentions but try this instead:
File newFile = new File(new File("folder\\").getAbsolutePath() + ".properties");
Trivially I missed that new File(".").getAbsolutePath() returns the project's absolute path with the . at the end so my folder whould be called as .folder. Next time I'll check twice.

Java mkdir + mkdirs always return false

I'm trying to create a new dir in Java but it doesn't work. I'm wondering why because I tried mkdir() first and then I tried mkdirs() which is supposed to create unexistant directories.
I wrote :
boolean status = new File("C:\\Users\\Hito\\Desktop\\test").mkdir();
// status = false
then I wrote
boolean status = new File("C:\\Users\\Hito\\Desktop\\test").mkdirs();
// status still = false.
A clue ?
This is faster to type, and does not need double slashes:
boolean status = new File("C:/Users/Hito/Desktop/test").mkdir();
if you still get errors, check if the parent directory exists, and if file is writeable.
String path = "C:/Users/Hito/Desktop/";
File file = new File(path);
If (!path.exists()) {
System.out.println("path does not exist:" + path);
} else {
File dir = new File(path + "test");
if (!dir.canWrite()) {
System.out.println("dir not writeable" + path + "test");
}
}
File file = new File("C:/Users/Hito/Desktop/test");
file.mkdirs();
file.createNewFile();
Check your permissions
Try it:
boolean status = new File("C:\\Users\\Hito\\Desktop\\test").canWrite();
It's kinda strange because I used the windows search and I could find my directory BUT it's not located at :
C:\Users\Hito\Desktop
but at :
C:\Users\Hito\Desktop\Dropbox\Stage\Applic_WIDT
which is the directory containing my application.

Java. Files and folders. Can't define the type

Good Day!
I wrote the method in Java which must search files in folders and do some operations with them.
So the problem is that when I try to check what I have (file or dir) I receive nothing in both cases! But as i can see paths look correct.
How can I fix this problem?
Here is the code:
public void searchInDir(){
File inputFile = new File( this.fileName );
String[] namesOfFilesDir = inputFile.list();
for ( int i = 0; i < namesOfFilesDir.length; i++ )
{
String normalPath = this.getNormalPath(inputFile.getCanonicalPath()); //C:\User -> C:\\User
// Two separators for correcting path to file
String pathToCurrentFile = normalPath + File.separator + File.separator + namesOfFilesDir[i];
File f = new File( pathToCurrentFile, namesOfFilesDir[i] );
System.out.printf("FileName=%s, Path=[%s]\n", namesOfFilesDir[i], pathToCurrentFile);
System.out.println(f.isDirectory());//False
System.out.println(f.isFile());//False too
//Some other code
}
}
For example this.fileName consists path to folder ( and this folder consists one folder and 2 files).
I got next:
FileName=Readme.txt, Path=[C:\\workspace\\Grep\\t\\Readme.txt]
false
false
FileName=t2, Path=[C:\\workspace\\Grep\\t\\t2]
false
false
FileName=test.txt, Path=[C:\\workspace\\Grep\\t\\test.txt]
false
false
Ok. Program says that.
Lets print next code as an example.
File f = new File("C:\\workspace\\Grep\\t\\Readme.txt");
System.out.println(f.isFile());
Program will print ”True”.
This part makes no sense:
String pathToCurrentFile = normalPath + File.separator + File.separator + namesOfFilesDir[i];
File f = new File( pathToCurrentFile, namesOfFilesDir[i] );
Even if we forget about the double separator for the time being, it makes no sense to first construct the file name by adding namesOfFilesDir[i], then construct a File() object using the two-argument constructor which basically adds namesOfFilesDir[i] once more. Try printing f.getAbsolutePath() and you'll see what I mean. It should have probably been something like:
File f = new File( normalPath, namesOfFilesDir[i] );
Probably the file doesn't exist, so it is neither a file nor a directory. Try printing the output of f.exists() as well.
Did you notice the duplicate file separator in your path?
I think that perhaps your paths are not correct. Both isFile() and isDirectory() only return true if the file/directory actually exists. Have you tried calling exists() on the file? Also, I'm suspicious of what your getNormalPath() method is doing - I think it might be mangling the filenames.
The 1st System.out.println is missleading!
It would have been better to output the path of f.
Anyway, according the output:
FileName=Readme.txt, Path=[C:\workspace\Grep\t\Readme.txt]
f will be C:\workspace\Grep\t\Readme.txt\Readme.txt
that is, namesOfFilesDir[i] is being appended twice!
It would be easier/better to work just with instances of File directly:
File inputFile = new File(this.fileName);
File[] files = inputFile.listFiles();
for (File f : files) {
System.out.printf("FileName=%s, Parent=[%s]\n", f.getName(), f.getParent());
System.out.println(f.isDirectory());
System.out.println(f.isFile());
//Some other code
}

url = new java.net.URL()

url = new java.net.URL(s) doesn't work for me.
I have a string C:\apache-tomcat-6.0.29\webapps\XEPServlet\files\m1.fo and need to make a link and give it to my formatter for output, but malformed url recieved. It seems that it doesn't make my string to url.
I want also mention, that file m1.fo file is in files folder, in my webapp\product\, and I gave the full path to string like: getServletContext().getRealPath("files/m1.fo"). What I am doing wrong? How can I recieve the url link?
It is possible to get an URL from a file path with the java.io.File API :
String path = "C:\\apache-tomcat-6.0.29\\webapps\\XEPServlet\\files\\m1.fo";
File f = new File(path);
URL url = f.toURI().toURL();
Try: file:///C:/apache-tomcat-6.0.29/webapps/XEPServlet/files/m1.fo
It isn't preferable to write file:/// . Indeed it works on windows system,but in unix - there were problems.
Instead of using
myReq.put("xml", new String []{"file:" + System.getProperty("file.separator") +
getServletContext().getRealPath(DESTINATION_DIR_PATH) +
System.getProperty("file.separator") + xmlfile});
you can write
myReq.put("xml", new String [] {getUploadedFileURL (xmlfile)} );
, where
public String getUploadedFileURL(String filename) {
java.io.File filePath = new java.io.File(new
java.io.File(getServletContext().getRealPath(DESTINATION_DIR_PATH)),
filename);
return filePath.toURI().toURL().toString();
A file system path is not a URL. A URL is going to need a protocol prefix for one. To reference file system use "file:" in front of your path.

Categories

Resources