I'm currently learning Java I/O , when I compile this code :
import java.io.File;
public class Main {public static void main(String[] args){
//Creation of the File object
File f = new File("test.txt");
System.out.println("File absolute path : " + f.getAbsolutePath());
System.out.println("File name : " + f.getName());
System.out.println("Does it exist ? " + f.exists());
System.out.println("Is it a directory? " + f.isDirectory());
System.out.println("Is it a file ? " + f.isFile());
}
The problem is f.exists() and f.isFile()return false
How is that even possible ?
File f = new File("test.txt");
The above line doesn't create an physical file on the disk. it only creates a file object, with the name 'test.txt', thus File#exits() returns false.
You need to create an actual physical file in number of ways.
Using File
file.createNewFile()
using FileWriter
FileWriter writer = new FileWriter(f);
PS: same applies for File#isFile() returning false as well.
File is not a fileāit is just a descriptor of a native filesystem resource that may or may not exist. For example, you can do new File(path).createNewFile().
new File("test.txt") It creates a new File instance by converting the given pathname string into an abstract pathname not physical file.
you can call File#createNewFile(). It atomically creates a new, empty file named by this abstract pathname if and only if a file with this name does not yet exist.
there is nothing wrong with the program except the file location
there are two solutions
1 : you can store the file in the project directory , parallel to src folder
2 you can create the file with full path specified
File f = new File("D:/folder1/folder2/applicationname/src/test.txt");
Related
Let's suppose I have a zip file containing two elements: elem1 (created by linux command touch elem1) and elem2 (created by linux command mkdir elem2)
Now, in java, I use the following code to extract the content of the zip
// ...
// Suppose we have a valid inputStream on a zip file
// ...
ZipInputStream zipInputStream = new ZipInputStream(inputStream);
ZipEntry entry = zipInputStream.getNextEntry();
while (entry != null) {
int entrySize = (int) entry.getSize();
File file = Paths.get(extractPath).resolve(entry.getName()).toFile();
if (/*Condition to detect a directory*/) {
System.out.println("This is a directory");
FileUtils.forceMkdir(file);
} else if (/*Condition to detect an empty file*/) {
System.out.println("This is an empty file");
} else {
System.out.println("This is something else");
}
entry = zipInputStream.getNextEntry();
}
I would like to specify the right conditions to detect whether entry is a directory, or an empty file without extension. Knowing that these entries are still in memory and do not exist on the filesystem, the command file.isDirectory() always returns false; so I cannot not use it to check for directory.
Any ideas please ?
I created both an empty folder and an empty file without extension and evaluated them with the code below:
public static void main(String[] args) {
String path = System.getProperty("user.home") + File.separator + "Desktop" + File.separator;
File file = new File(path + "EmptyFile");
File folder = new File (path + "EmptyFolder");
System.out.println("Is 'folder' a folder? " + (Files.isDirectory(folder.toPath())? "Yes" : "No" ));
System.out.println("Is 'file' a folder? " + (Files.isDirectory(file.toPath())? "Yes" : "No" ));
}
The (not surprising) result:
Is 'folder' a folder? Yes
Is 'file' a folder? No
The reason why this works is because the function Files.isDirectory(...) looks in the file attributes set by the Operating System to determine whether the item being examined is a "File folder" or simply a "file". My assumption is that Zip programs do not contain such metadata (not even Windows zip). Therefore, "isDirectory" test cannot be performed using the Files.isDirectory(...) function. My quick research discovered that, the way to do this (and I am kind of shocked) is by examining the file name and check to see if the name ends with the file separator. In fact, this is how ZipEntry.isDirectory() works.
Attempting to zip an empty folder is not allowed for Windows zip (maybe allowed with other software?). However, I was able to include empty directories with 7-zip. That wasn't the only difference. The isDirectory() test failed when the zip was created with Windows zip because the file was skipped altogether. So, in order for this to work, create the zip file with zip software other than the one that comes with Windows. Then,
public static void main(String[] args) throws IOException {
String path = System.getProperty("user.home") + File.separator + "Desktop" + File.separator;
FileInputStream inputStream = new FileInputStream(path + "Desktop.zip");
ZipInputStream zipInputStream = new ZipInputStream(inputStream);
ZipEntry entry = zipInputStream.getNextEntry();
while (entry != null) {
File file = Paths.get(entry.getName()).toFile();
if (entry.isDirectory()) {
System.out.println(entry.getName() + " is a directory");
} else if (file.getName().endsWith(".lnk")) {
System.out.println(file.getName() + " is a shortcut");
} else {
System.out.println(entry.getName() + " is a file");
}
entry = zipInputStream.getNextEntry();
}
zipInputStream.close();
}
Outputs for me:
EmptyFile is a file
EmptyFolder/ is a directory
How We Test Wireless Routers _ PCMag_files/ is a directory
How We Test Wireless Routers _ PCMag_files/00hSyhn9j5PNrcOot1tMzz9.1578945749.fit_lim.size_100x100.png is a file
...
etc
One last note... obviously, if a ZipEntry is not a directory, it is a file. Therefore, no else if is needed. That is, unless you would like to make a distinction between file types. In the example above, I wanted to check if a particular file was a shortcut. Just keep in mind that this is not necessary. The logic should only test entries for isDirectory and if the test fails, it is simply a file.
package com.company;
public class Main {
public static void main(String[] args) {
java.io.File file = new java.io.File("image/us.gif");
System.out.println("Does it exist:" + file.exists());
System.out.println("The file has " + file.length() + "bytes");
System.out.println("Can it be read? " + file.canRead());
}
}
I copied this code from my book Introduction to Java Programming, and it compiles correctly but it doesn't create the file, and returns false and zero bytes for the methods. Can someone help please I will give best answer.
You will have to create the file manually unless it already exists. Creating a new File object should not be confused with creating a file in the filesystem.
To create the file you will have to use the method createFile(); which exists in the class File:
File someFile = new File("path.to.file");
someFile.createFile();
It would also be a good idea to check if the file exists before creating it to avoid overwriting it. this can be done by:
File someFile = new File("path.to.file");
if(!someFile.exists()) {
someFile.createFile();
}
This will create a new empty file. That means that it's length will be 0.
To write to the file you will need a byte stream. For example, using a FileWriter:
File test = new File("SomeFileName.txt");
FileWriter fw = new FileWriter(test);
fw.append("Hello! :D");
fw.close();
Note: Some methods i used in the examples above throw exceptions which you will have to handle.
How to pass multiple files to another class?
I am developing an application which first compresses the image and after that it'll convert it into pdf.
The program which i have written works well seperately ie; it compresses the image and then in another project i use the path where the image are stores to convert it to pdf.
Now i want to have both these codes in the same project and i am encountering the problem where i am creating a loop where i pass the path name one by one. The source path works well but i need to specify the destination path which changes the name dynamically this where i am facing the problem. I have attached the code below please tell me what to do.
System.out.println("before convert");
Conversion cc = new Conversion();
File directory = new File(Success);
File[] files = directory.listFiles();
if(files!=null)
{
for(File f:files){
String path = f.getName();
System.out.println("The Name of file is="+path);
cc.createPdf("path" , "output", true);
System.out.println("the file is ="+output+".pdf");
System.out.println("after convert");
}
}
In the above code i need to change the output file name dynamically here cc.createPdf("path" , "output", true);
A simple implementation would be to keep a counter outside loop and increment it before appending it to output file name
int counter = 0;
for(File f:files){
String path = f.getName();
System.out.println("The Name of file is="+path);
counter++; //increment the counter
cc.createPdf("path" , "output"+counter, true); // append it to output
System.out.println("the file is ="+output+".pdf");
System.out.println("after convert");
}
For more robustness, counter can be replaced by UUID generator, System time in milliseconds etc
Im guessing your having trouble getting a File object with a newly created .pdf extension, you will have to adapt this to your code but it should be pretty straight forward.
File inputFile = new File("c:\\myimage.png");
String fileName = inputFile.getName();
File pdfFile = new File(inputFile.getParent(), fileName.substring(0, fileName.indexOf(".")) +".pdf");
System.out.println(inputFile + " " + pdfFile);
I think you should keep things simple by just appending ".pdf" to the names. The fact that you are processing a directory ensures that the source file names are unique. Hence, the new ".pdf" names would also be unique.
Assuming your output files land in the same directory, it also becomes much easier to sort files by names and know immediately which ".pdf" files correlate to which source files.
So, your output file name simply becomes
String path = f.getName();
String output = path.substring(0, path.lastIndexOf('.')) + ".pdf";
In Java on Windows, how do we know that a file or folder is read-protected?
I try with canRead() et setReadable() :
String pathFile = "D:/Folder";
File f = new File(pathFile);
System.out.println("Is Protected => " + f.setReadable(true)==true);
but it not solve my problem
Thank you
canWrite method is true if and only if the file system actually contains a file denoted by this abstract pathname and the application is allowed to write to the file; false otherwise.
File lFile = new File("Sample.txt")
lFile.canWrite();
This is the code I tried. But this returns false even if the file exists. The variables FilePath and FileName is obtained from the UI.
File exportFile = new File("\""+FilePath + "\\"+ FileName+"\"");
boolean exists = exportFile.exists();
if (!exists) {
System.out.println("File does not exists");
}
else{
System.out.println( "File exists.");
}
What is the proper way to do this? And BTW, How can I prompt the user to replace or rename the FileName?
replace
File exportFile = new File("\""+FilePath + "\\"+ FileName+"\"");
with
File exportFile = new File(FilePath + "\\" + FileName);
There is no need for quoting the file name. Even if it contains spaces.
I think the problem might be caused by the way you get the file path, since you are getting it from UI, i should point out that you don't have to construct the path, you can either use getAbsolutePath() or getPath() methods provided in the java.io.File class.