Reputation: 173
I am working on building a web application around a Standalone JAR application. Essentially the JAR application reads an input file, processes it and generates an output file.
The input file is placed like this, right next to the JAR.
The code for the JAR application is shown below.
public class FileReadWriteApp {
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
try {
File inFiles = new File("../inputFiles");
if (!inFiles.exists()) {
if (inFiles.mkdirs()) {
System.out.println("Input directory is created!");
} else {
System.out.println("Failed to create input directory!");
}
}
Path inputPath = FileSystems.getDefault().getPath("testInput.txt", new String[0]);
Files.copy(inputPath, new FileOutputStream("../inputFiles/testInput.txt"));
String content = new String(Files.readAllBytes(inputPath));
String parsedInput = content.toUpperCase();
new File("../outputFiles").mkdirs();
Files.write(Paths.get("../outputFiles/testOutput.txt"), parsedInput.getBytes());
} catch (IOException exc) {
System.out.println(exc);
System.exit(1);
}
}
Upon executing the JAR in the Command prompt it successfully creates inputFiles and outputFiles folders at one level higher than the JAR file and puts the corresponding input/output files correctly.
However, when I add the JAR as a dependency in the Spring based web application that I am building and place the input file and JAR file at the same location, it can't access the input file.
In the Spring web application I have placed both the input file and the JAR file as shown below:
I can even see them come up in the Target folder in the lib directory as shown below:
In my Spring Controller method, I am executing the main()
method of the JAR file like this:
String[] args = new String[] { "" };
filereadwriteapp.FileReadWriteApp.main(args);
However, in the console I see these messages:
Input directory is created!
java.nio.file.NoSuchFileException: testInput.txt
I am not able to understand why the application can't find the file testInput.txt
?
Can somebody kindly guide me regarding fixing this issue?
Is there some specific location where I should place the testInput.txt
file so that the "dependency" JAR file can access it?
Kindly note that I am not loading a resource from WEB-INF directory from within the Web Application. In my case, I am having issue with a "dependency" JAR loading a resource from a relative path to itself.
Any help in this regard would be highly appreciated.
Upvotes: 0
Views: 1104
Reputation: 111
FileSystems api returns different path , so you need to use classpath to get the file as shown below
ClassLoader classLoader = getClass().getClassLoader();
File file = new File(classLoader.getResource("testInput.txt").getFile());
Upvotes: 0