How to pass arguments to pre compiled java code - java

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.

Related

Java loses the last "/" character of the path

I am developing a java application to perform operations with files.
In particular, I perform move and copy of files .. and I have programmed two functions.
Functions take strings such as sourcePath and targetPath as parameters.
I am developing on a mac, and I have given 777 permissions to the folders I need.
But I have the problem, that when I pass paths to the copyFile and moveFile functions I lose the last "/" of the path and consequently get a java.nio.File: NoSuchFileException exception.
I have read both the Java and online documentation but have not found any answers.
I accept any suggestion or advice ... I just add that by manually forcing the path inside the function, then not passing sourcePath and targetPath, the two functions behave as they should.
copyFile:
public static boolean copyFile(String sourcePath, String targetPath) throws IOException {
boolean fileCopied = true;
// if i pass sourcePath i lost the last /
File dirFiles = new File("/Users/myname/Documents/deleghe/remote/F24_CT/deleghe_da_inviare_a_icbpi/");
File[] listOfFiles = dirFiles.listFiles();
String dest = "/Users/myname/Documents/deleghe/local/F24_CT/deleghe_da_inviare_a_icbpi/";
for (File file : listOfFiles) {
Files.copy(file.toPath(),
(new File(dest + file.getName())).toPath(),
StandardCopyOption.REPLACE_EXISTING);
}
return fileCopied;
}
moveFile:
public static boolean moveFile(String sourcePath, String targetPath) throws IOException {
boolean fileMoved = true;
// if i pass sourcePath i lost the last /
File dirFiles = new File("/Users/myname/Documents/deleghe/remote/F24_CT/deleghe_da_inviare_a_icbpi/");
File[] listOfFiles = dirFiles.listFiles();
String dest = "/Users/myname/Documents/deleghe/remote/F24_CT/deleghe_inviate/";
for (File file : listOfFiles) {
if (file.length() >= 968 && file.length() <= 2057) {
Files.move(file.toPath(),
(new File(dest + file.getName())).toPath(),
StandardCopyOption.REPLACE_EXISTING);
System.out.println("File spostato correttamente: " + file.getName() + "!! \n");
} else {
System.out.println("Non รจ stato possibile spostare il file: " + file.getName() + "!! \n");
}
}
return fileMoved;
}
try to use Paths.get(dest, file.getName()).toUri() instead of dest + file.getName() (it is not best practice)
you are not losing anything, you just reading files from directory and your code is working without any exception. Check your directories and files inside them one more time

Java get resource is not working

I try to read a resource file from my application but it doesn't work.
Code:
String filename = getClass().getClassLoader().getResource("test.xsd").getFile();
System.out.println(filename);
File file = new File(filename);
System.out.println(file.exists());
Output when I execute the jar-file:
file:/C:/Users/username/Repo/run/Application.jar!/test.xsd
false
It works when I run the application from IntelliJ but not when I execute the jar-file. If I open my jar-file with 7-zip test.xsd is located in the root-folder. Why isn't the code working when I execute the jar-file?
Also, File refers to actual OS file-system files; in the OS's file-system, there is only a jar file, and that jar file is not a folder. You should either extract the contents of the URL to a temporary file, or operate with its bytes in-memory or as a stream.
Note that myURL.getFile() is returning a String representation, and not an actual File. In a similar way, this will not work:
File f = new URL("http://www.example.com/docs/resource1.html").getFile();
f.exists(); // always false - will not be found in the local filesystem
A nice wrapper could be the following:
public static File openResourceAsTempFile(ClassLoader loader, String resourceName)
throws IOException {
Path tmpPath = Files.createTempFile(null, null);
try (InputStream is = loader.getResourceAsStream(resourceName)) {
Files.copy(is, tmpPath, StandardCopyOption.REPLACE_EXISTING);
return tmpPath.toFile();
} catch (Exception e) {
if (Files.exists(tmpPath)) Files.delete(tmpPath);
throw new IOException("Could not create temp file '" + tmpPath
+ "' for resource '" + resourceName + "': " + e, e);
}
}

Download entire FTP directory in Java (Apache Net Commons)

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

Java Load File to pass to other class

What is the best way to load a file into a java application to be passed to another class?
Currently I am using JFileChooser to select a source file (C, C++, Java) which is then passed to an executable called src2srcml. My code runs the src2srcml tool which takes the source file and converts it to an XML which is then stored in my workspace (eclipse). I then want to take that XML file and pass it over to another class to be analysed. As you can see below I am currently trying the getResources method. It can find the file fine but I don't actually know how to pass it to the class UnitXMLReader. GetResources returns a URL to the file but the other class needs the filepath. Is there a better way to find the file?
JButton btnRunSourceCode = new JButton("Run Source Code");
btnRunSourceCode.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
//------Check for loaded file ----//
if(filePath == null){
textArea.setText("Please Load a source file (C, C++, Java)");
}
else{
try{
int c;
textArea.setText("Converting Source Code to XML");
String workspace = System.getProperty("user.dir");
String classPath = System.getProperty("java.class.path");
String[] commands = {"/bin/bash", "-c", "cd " + workspace + " && ./src2srcml --position " + selectedFile.getName() + " -o " + classPath + "/xmlParseGUI/targetFile.xml"};
Process src2XML = Runtime.getRuntime().exec(commands);
InputStream in1 = src2XML.getErrorStream();
InputStream in2 = src2XML.getInputStream();
while ((c = in1.read()) != -1 || (c = in2.read()) != -1) {
System.out.print((char)c);
}
src2XML.waitFor();
}
catch(Exception exc){/*src2srcml Fail*/}
}
ParallelXMlGUI c = new ParallelXMlGUI();
Class<? extends ParallelXMlGUI> cls = c.getClass();
// finds resource relative to the class location
URL url = cls.getResource("targetFile.xml");
//UnitXMLReader.ChosenFile = filePath;
//UnitXMLReader.main(null);
System.out.println("Value = " + url);
File file = new File(classPath + "/xmlParseGUI/targetFile.xml);
Java has a file class for handling files. Try creating a new File object that points to that file. Then pass the new File object.
Or you could try relative path:
File file = new File("/smlParseGUI/targetFile.xml");
A couple File methods:
file.getPath();
file.getString();

Code cannot find my file

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.

Categories

Resources