I have a file in my src/main/resources folder, the location of which i am passing in library function, but the file is not being read.
here is how the folder structure looks on decompiling the war
.
I have a file in my src/main/resources folder(Intuit.cto.gateway.aws.preprod.jks), the location of which i am passing in library function, but the file is not being read.
here is how the folder structure looks on decompiling the war.
when i create a simple maven project and try to do the same, i am able to access the file from src/main/resources
when i decompile my sample project it looks like this
To access the file, i am using this code :
public static void main(String args[])throws Exception{
FileReader fr=new FileReader("src/main/resources/filename");
int i;
while((i=fr.read())!=-1)
System.out.print((char)i);
fr.close();
}
how to solve this problem ?
You can't do it the way you want to.
Your path is most likely incorrect. Unzip your *.war file and see that src/main is no more.
If the war file is not exploded, you can't access its content by using simply path passed to a File* class, because your file is packaged as in zipped into standard location in a ZIP file with file extension WAR.
If your destination requires File or path which is passed to FileReader you have to read this file out of WAR file (using ClassLoader.getResourceAsStream()) and copying it out to a temporary location like File.createTempFile() or System.getProperty("java.io.tmpdir").
A resource (on the class path) is not necessarily a file system file. If the usage cannot deal with just an InputStream, one needs to create a temp file.
Path tempFile = Files.createTempFile("phoneid-", ".jks");
InputStream res = getClass().getResourceAsStream("/Intuit/gateway/preProd.jks");
// Case-sensitive, absolute path on the class path.
Files.copy(res, tempFile);
// Maybe:
//tempFile.toFile().deleteOnExit();
String param = tempFile.toString();
(A result null for getResource/getResourceAsStream indicates a wrong path.)
A partial solution would also be to check the URL of the resource, whether has the "file:" protocol, and not "jar:file:" (packed in a zip format, like jar, ear or war).
URL url getClass().getResource("/Intuit/gateway/preProd.jks");
With a class, the path can either be relative to the class package directory, or absolute ("/..."). If using the ClassLoader instead the path is always absolute, and should be written without / in front.
Related
I want to want to use input stream with a file "NewFile.java", the code I have works fine if the file is situated in the same folder as the .class file that is performing the action. But once I move I get null reference.
I have tried using absolute and relative paths with and without a '/' at the start.
InputStream in = getClass()
.getResourceAsStream("NewFile.java");
I would like to source the file when it is located in the root directory of the project.
Better use InputStream in= new FileInputStream(new File("path/to/yourfile"));
The way you are using it now is as a resource which has to be in the class path.
getResourceAsStream() is not meant to open arbitrary files in the filesystem, but opens resource files located in java packages. So the name "/com/foo/NewFile.java" would look for "NewFile.java" in the package "com.foo". You cannot open a resource file outside a package using this method.
There is a distinction between files on the file system, and resources, on the class path. In general a .java source file won't be copied/added to the class path.
For a class foo.bar.Baz and a resource foo/bar/images/test.png one can use
Baz.class.getResourceAsStream("images/test.png")
Baz.class.getResourceAsStream("/foo/bar/images/test.png")
As you see the paths are class paths, possibly inside .jar files.
Use file system paths:
Path path = Paths.get(".../src/main/java/foo/bar/Baz.java");
InputStream in = Files.newInputStream(path);
List<String> lines = Files.readAllLines(path);
List<String> lines = Files.readAllLines(path, StandardCharsets.ISO_8859_1);
Files.copy(path, ...);
I'm using java.io.FileReader:
FileReader fileReader = = new FileReader(filepath)
When running locally, a typical filepath would be
"/Users/acypher/Desktop/enrollment.json"
Then, when I deploy to Tomcat on AWS, I want to put the file somewhere in the build that FileReader can find -- any place is fine with me, but I haven't been able to find any location that works, since I don't know what root directory FileReader is using.
The .war expands to a folder which includes META-INF and WEB-INF subfolders. WEB-INF contains a "classes" folder, which contains files that are locally in my src/main/resources/ folder, so that seems like a good location. But I don't know how to set the filepath to refer to this location.
I'm using IDEA with Spring Boot.
The /src/main/resources/ is definitely the way to go. You can access the files in this folder with the methods Class.getResource(String) or Class.getResourceAsStream(String) (see: https://docs.oracle.com/javase/7/docs/api/java/lang/Class.html#getResourceAsStream(java.lang.String)).
For example, if you have your file in /src/main/resources/myFolder/myFile.myExt, you can either call:
this.getClass().getResource("myFolder/myFile.myExt")
this.getClass().getResourceAsStream("myFilder/myFile.myExt")
which, in a static context, where you don't have the this reference, become, respectively:
MyClass.class.getResource...
MyClass.class.getResourceAsStream
In the first case you should (I didn't verify it myself) be able to create a File instance like this: File file = new File(this.getClass().getResource("myFolder/myFile.myExt").toURI()), and from that the FileReader instance; while in the second case, you have at your disposal the InputStream which you can use to read the file.
As you can see, the file is right inside the same folder where the class file is. While I tried to have it print the path to it, that is a bummer because no matter what name I type it will always type a full path to that invented file name. The file is comma separated, that I copied pasted into gedit and tried all kinds of extensions, csv, txt and no extension.
What I am trying to do is import it into an array, but the error is clear, no such file or directory.
You can try getting the path of the root folder from System.getProperty(). Then just append underlying folder names till the required filename.
private static String CLASS_PATH = System.getProperty("user.dir");
public static String FILE_PATH= CLASS_PATH + File.separator + "Source Packages"+ File.separator + "javaapplication2"+ File.separator + "pedidos.txt";
You should place files that are needed by your program in the classpath of your application so that they will get packaged in your JAR file. You can then read them with getResourceAsStream() Here's an idea of how that would work.
public class ArrayMain {
public static void main(String[] args) {
Scanner in = new Scanner(ArrayMain.class.getResourceAsStream("numbers.txt"));
String[] numbers = in.nextLine().split(",");
for (int i = 0; i < numbers.length; i++) {
System.out.println(numbers[i]);
}
}
}
The file numbers.txt is a simple file that looks like this:
1,2,3,4,5,6,7,8,9
Do not use relative paths to get files packaged with your application, it's dirty and senseless.
Path are relative to the folder in which was launched the java process. It's (usually) not your application source directory and never you file.java directory.
Even then, it's a terrible practice to put files (resources) inside your application source code. Because your java files needs to be compilated (and often packaged into a jar), the current architecture is likely to have no more meaning once packaged.
If you want to refer to a file on your computer, put it in a sensible folder (like /user/documents) and get it with its absolute path.
If you want the file to be packaged with your application, put it in a resource folder, package it in a jar and get the path with a classpath:// scheme.
The file needs to be placed at the root folder of your project.
I have a jav aproject which is build through ant. It write the class files to output/classes/com/... path. One of my java classes needs input stream read from a file that is in a folder one level above output folder. Looks like if copy the file to the package folder under outptu/classes, it seems to work. But I do not want to palce my config file in output folder as it will be cleaned when I do ant clean. I want it to find it look above the output folder, in config folder and load it.
public static final String CONFIG_FILE="/../../../../../../../Config.txt";
public static ConfigObj getConfigObj() throws IOException {
InputStream i=ConfigLoader.class.getResourceAsStream(CONFIG_FILE);
...
I want to know when I want to give raltivepath, what should it be relative to. I tried looking up , it says relative to classloader. What is classloader in this case? Is it output/classes/com....../config folder where my ConfigLoader.class lives?
The problem is that getResourceAsStream() will only load resources from the classpath. I guess you only have output/classes on your classpath, so you will never be able to load the config file via getResourceAsStream() if it's outside that directory. Use a File with an absolut path pointing to the file, or place it in your classpath.
I need to acces (create and read) a file from a JAR file (executable jar),
and that file should be created in the same directory as the JAR
I tried
this.getClass().getResource("myFile")
but since the jar has packages in it, it won't work..
I also tried write just
File f = new File("myFile");
f.createNewFile();
and that works if i execute the JAR from the terminal, but if i execute the JAR by double-clicking it, the file is created in my home directory -.-''
how do i access a file being SURE that that file is in the SAME directory as the JAR file?
(of course also getting the jar absolute path would do the trick since i can get the parent folder from it)
This will give you the full path to the Jar:
String path = this.getClass().getProtectionDomain().getCodeSource().getLocation().getPath();
EDIT: sorry, was in javascript mode when I wrote that :). As was so politely requested, in a static method you should be able to do this:
String path = Me.class.getProtectionDomain().getCodeSource().getLocation().getPath();
(where the class name is Me).