I have written a short program that will find a file I have made and print some of its details. It executes all right, but it cannot detect the file size or if it is hidden or not. E.G.
file path: C:\temp\filetext.txt last modified: 0 file size: 0 Is file hidden?false
The file does exist in the temp folder on C. I'm not really sure what the problem is
public void Q1()
{
String fileName = "filetext.txt";
getFileDetails(fileName);
}
public void getFileDetails(String fileName)
{
String dirName = "C:/temp/";
File productsFile = new File(dirName + fileName);
long size = productsFile.length();
System.out.println("file path: " + productsFile.getAbsolutePath() + " last modified: " + productsFile.lastModified() + " file size: " + productsFile.length() + " Is file hidden?" + productsFile.isHidden());
}
File does not need a physical file to work with. Therefore your File object can exist even if the physical file it is supposed to represent does not exist/cannot be found. Check the JavaDoc for length() and lastModified(), they both return 0L in case for example the file does not exist. So make sure your File objects is linked to an existing file on your file system by calling file.exists() before calling the other methods.
Related
I need to process a high volume of resumes. And want to use this parser:
https://github.com/antonydeepak/ResumeParser
But you run it in powershell with the file to read and the output file.
But I do not know how to automate this, so it read a whole folder containing the resumes.
I know some Java, but cant open the code. Is scripinting in powershell the way to go?
Thanks!
> java -cp '.\bin\*;..\GATEFiles\lib\*;..\GATEFILES\bin\gate.jar;.\lib\*'
code4goal.antony.resumeparser.ResumeParserProgram <input_file> [output_file]
Either make a batch file from an edited directory listing, or write a program.
As this is stackoverflow:
So starting with the same classpath (-cp ...) you can run your own program
public void static main(String[] args) throws IOException {
File[] files = new File("C:/resumes").listFiles();
File outputDir = new File("C:/results");
outputDir.mkDirs();
if (files != null) {
for (File file : files) {
String path = file.getPath();
if (path.endsWith(".pdf")) {
String output = new File(outputDir,
file.getName().replaceFirst("\\.\\w+$", "") + ".json").getPath();
String[] params = {path, output);
ResumeParserProgram.main(params);
// For creating a batch file >x.bat
System.out.println("java -cp"
+ " '.\\bin\\*;..\\GATEFiles\lib\\*;"
+ "..\\GATEFILES\\bin\\gate.jar;.\\lib\\*'"
+ " code4goal.antony.resumeparser.ResumeParserProgram"
+ " \"" + path + "\" \"" + output + "\"");
}
}
}
}
Check that this works, that ResumeParserProgram.main is reenterable.
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.
I am trying to recursively iterate through the entire root directory that I arrive at after login to the FTP server.
I am able to connect, all I really want to do from there is recurse through the entire structure and and download each file and folder and have it in the same structure as it is on the FTP. What I have so far is a working download method, it goes to the server and gets my entire structure of files, which is brilliant, except it fails on the first attempt, then works the second time around. The error I get is as follows:
java.io.FileNotFoundException: output-directory\test\testFile.png
(The system cannot find the path specified)
I managed to do upload functionality of a directory that I have locally, but can't quite get downloading to work, after numerous attempts I really need some help.
public static void download(String filename, String base)
{
File basedir = new File(base);
basedir.mkdirs();
try
{
FTPFile[] ftpFiles = ftpClient.listFiles();
for (FTPFile file : ftpFiles)
{
if (!file.getName().equals(".") && !file.getName().equals("..")) {
// If Dealing with a directory, change to it and call the function again
if (file.isDirectory())
{
// Change working Directory to this directory.
ftpClient.changeWorkingDirectory(file.getName());
// Recursive call to this method.
download(ftpClient.printWorkingDirectory(), base);
// Create the directory locally - in the right place
File newDir = new File (base + "/" + ftpClient.printWorkingDirectory());
newDir.mkdirs();
// Come back out to the parent level.
ftpClient.changeToParentDirectory();
}
else
{
ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE);
String remoteFile1 = ftpClient.printWorkingDirectory() + "/" + file.getName();
File downloadFile1 = new File(base + "/" + ftpClient.printWorkingDirectory() + "/" + file.getName());
OutputStream outputStream1 = new BufferedOutputStream(new FileOutputStream(downloadFile1));
boolean success = ftpClient.retrieveFile(remoteFile1, outputStream1);
outputStream1.close();
}
}
}
}
catch(IOException ex)
{
System.out.println(ex);
}
}
Your problem (well, your current problem after we got rid of the . and .. and you got past the binary issue) is that you are doing the recursion step before calling newDir.mkdirs().
So suppose you have a tree like
.
..
someDir
.
..
someFile.txt
someOtherDir
.
..
someOtherFile.png
What you do is skip the dot files, see that someDir is a directory, then immediately go inside it, skip its dot files, and see someFile.txt, and process it. You have not created someDir locally as yet, so you get an exception.
Your exception handler does not stop execution, so control goes back to the upper level of the recursion. At this point it creates the directory.
So next time you run your program, the local someDir directory is already created from the previous run, and you see no problem.
Basically, you should change your code to:
if (file.isDirectory())
{
// Change working Directory to this directory.
ftpClient.changeWorkingDirectory(file.getName());
// Create the directory locally - in the right place
File newDir = new File (base + "/" + ftpClient.printWorkingDirectory());
newDir.mkdirs();
// Recursive call to this method.
download(ftpClient.printWorkingDirectory(), base);
// Come back out to the parent level.
ftpClient.changeToParentDirectory();
}
A complete standalone code to download all files recursively from an FTP folder:
private static void downloadFolder(
FTPClient ftpClient, String remotePath, String localPath) throws IOException
{
System.out.println("Downloading folder " + remotePath + " to " + localPath);
FTPFile[] remoteFiles = ftpClient.listFiles(remotePath);
for (FTPFile remoteFile : remoteFiles)
{
if (!remoteFile.getName().equals(".") && !remoteFile.getName().equals(".."))
{
String remoteFilePath = remotePath + "/" + remoteFile.getName();
String localFilePath = localPath + "/" + remoteFile.getName();
if (remoteFile.isDirectory())
{
new File(localFilePath).mkdirs();
downloadFolder(ftpClient, remoteFilePath, localFilePath);
}
else
{
System.out.println("Downloading file " + remoteFilePath + " to " +
localFilePath);
OutputStream outputStream =
new BufferedOutputStream(new FileOutputStream(localFilePath));
if (!ftpClient.retrieveFile(remoteFilePath, outputStream))
{
System.out.println("Failed to download file " + remoteFilePath);
}
outputStream.close();
}
}
}
}
import java.io.File;
class AttriDemo{
public static void main(String args[]){
File f1 = new File("FileIO/file.txt");
System.out.println("File name : " + f1.getName());
System.out.println("File path : " + f1.getPath());
System.out.println("File AbsPath : " + f1.getAbsolutePath());
System.out.println("File parent : " + f1.getParent());
f1.setWritable(true);
if(f1.canWrite())
{
System.out.println("File is Writeable");
}
else
{
System.out.println("File is not Writeable");
}
if(f1.canRead())
{
System.out.println("Is readable");
}
else
{
System.out.println("File is not readable");
}
}
}
I the file is readable and writable in real...
then I tried setting it to Writable explicitly but still the output shows it as the file is not writable!!
output:
....
The file is not writable.
The file is not readable.
File f1 = new File("D:/javaProgs/FileIO/AttriDemo.java");
doing this helps solve the problem.
but can someone explain how? I mean the file was in the same directory and the statements above were running just fine. e.g getName() getParent()
What's fooling you is you can create a File object regardless of the path you specified exists or not and you can call all those getParent, getPath functions on that object.
You can create a File object that's not backed by a real file for various reasons like to check if it exists or to create a file specified by that objects path and name.
You can use File.exists() to see if file really exists on file system.
I am looking to get similar behaviour to what you get in Windows when you copy and paste a file in the same directory.
For e.g, if you've copy/paste a file called foo.txt, it will create foo Copy.txt and if you paste it once more, it creates foo Copy(2).txt and if you copy/paste foo Copy.txt, foo Copy Copy.txt is created.
Is there a Java utility function that does this? I've looked at File.createTempFile but the filename it generates is too long and contains a UID-like substring.
By using the FileChooser in combination with the "showSaveDialog"-method you will get the result you want, because java is then using the OS behaviour for existing files.
Sometimes, you just have to do the work first, it will give you an appreciation for the API. Then you can write your own utility methods
File original = new File("build.xml");
String path = original.getAbsoluteFile().getParent();
String name = original.getName();
String ext = name.substring(name.indexOf("."));
name = name.substring(0, name.indexOf("."));
name = path + File.separator + name;
int index = 1;
File copy = new File(name + " (" + index + ")" + ext);
while (copy.exists()) {
index++;
copy = new File(name + " (" + index + ")" + ext);
}
System.out.println(copy);