JUNIT : Get the input file from the file path in config folder - java

#Test
public void testProviderDetails_ValidFile()
{
ClassLoader classLoader = getClass().getClassLoader();
// Throws null pointer exception here
File file = new File(classLoader.getResource("services/src/text/resources/config/test.txt").getFile());
String filePath = file.getAbsolutePath();
}
I want to get the file path which is placed in the
src/test/resources/config folder.
But i am getting null pointer exception as i mentioned above.Can any help me regarding this ??
Is anything i have missed in the above code ?
I have also tried the below codes :
File file = new File(classLoader.getResource("c:/dev/Provider_Services/services/src/text/resources/config/test.txt").getFile()); and
File file = new File(classLoader.getResource("test.txt").getFile());
File file = new File(classLoader.getResource("config/test.txt").getFile());
Got the same error !!

I assume you are using Maven and its default settings.. so,src/test/resources is already in the classpath. So, just give config/test.txt as the parameter in the getresource method. It will work.

Related

How to load a png File as Java File from resource Folder

The way I go is
Resource iconHomeResource = new ClassPathResource("/assets/icons/icons8-home-16.png");
//print iconHomeResource.exists() IS TRUE
File iconHome = iconHomeResource.getFile() //throws FileNotFoundException.
In the past I used something like this.
/** This Work inside IDE but not in production*/
public File loadEmployeesWithSpringInternalClass()
throws FileNotFoundException {
return ResourceUtils.getFile(
"classpath:data/employees.dat");
}
I read some similiar Questions/Answeres here on SoF but not of them worked for me.

Cannot be resolved to absolute file path because it does not reside in the file system

My Code:
XWPFDocument doc = new XWPFDocument(OPCPackage.open(ResourceUtils.getFile("classpath:assets/OPTIONS_" + jubilar1.getJubiLanguage().toUpperCase() + ".docx")));
I have already tried instead of .getFile(), extractJarFileFromURL or resource.getInputStream() but all this does not work. When I package my project and run it as a jar file and it tries to open the following file it always returns the following message.
Error:
java.io.FileNotFoundException: class path resource [assets/OPTIONS_DE.
docx] cannot be resolved to absolute file path because it does not
reside in the file system:
jar:file:/home/tkf6y/IdeaProjects/hrapps/backend/target/backend-3.0.0.jar!/BOOT-INF/classes!/assets/OPTIONS_EN.docx
So yes it was the problem, as you are now using an InputStream as I suggested. The problem was (and always has been) the getFile stuff. What I suggest to do is don't use what you have now but rather do a new ClassPathResource(your location).getInputStream()) instead, it is easier, or even use a ResourceLoader (a Spring interface you can inject) and then use the path you had an again use getInputStream(). –
This works for me.
String strJson = null;
ClassPathResource classPathResource = new ClassPathResource("json/data.json");
try {
byte[] binaryData = FileCopyUtils.copyToByteArray(classPathResource.getInputStream());
strJson = new String(binaryData, StandardCharsets.UTF_8);
} catch (IOException e) {
e.printStackTrace();
}

File (.txt) cannot be found

I am creating a stock market simulator (beginner) and I made a .txt file to save the stock symbol and name within a file. I am having an issue where my code is unable to find the file on my desktop.
public static void load() throws FileNotFoundException {
File file = new File("/Users/dhruvchaudhari/Desktop/stocks.txt");
Scanner scan = new Scanner(file);
while ((scan.hasNextLine())) {
System.out.println(scan.nextLine());
}
}
The error it is throwing is as such
java.io.FileNotFoundException: /Users/*username*/Desktop/stocks.txt (No such file or directory)
I'm on Mac and I checked the directory for the file directory and it should be correct. Any suggestions?
You can check the current working directory to confirm the path of your file by adding System.out.println("Working Directory = " + System.getProperty("user.dir"));
this will return the path you can debug this to get the idea of path in your application.
Also you can add read the file if its not there the code will create it for so you can add your metadata into the generated file.
By using this approach I hope you can move ahead.
public static void load() throws IOException {
File yourFile = new File(path);
yourFile.createNewFile(); // if file already exists will do nothing
Scanner scan = new Scanner(yourFile);
while ((scan.hasNextLine())) {
System.out.println(scan.nextLine());
}
}
Obviously your path is wrong or the file doesn't exist. You can use the if statement to determine whether the file exists first, and create the file when it does not exist.

renaming file name inside a zip file

trying to rename internal file within a zip file without having to extract and then re-zip programatically.
example. test.zip contains test.txt, i want to change it so that test.zip will contain newtest.txt(test.txt renamed to newtest.txt, contents remain the same)
came across this link that works but unfortunately it expects test.txt to exist on the system. In the example the srcfile should exist on the server.
Blockquote Rename file in zip with zip4j
Then icame across zipnote on Linux that does the trick but unfortunately the version i have doesnt work for files >4GB.
Any suggestions on how to accomplish this? prefereably in java.
This should be possible using Java 7 Zip FileSystem provider, something like:
// syntax defined in java.net.JarURLConnection
URI uri = URI.create("jar:file:/directoryPath/file.zip");
try (FileSystem zipfs = FileSystems.newFileSystem(uri, Collections.<String, Object>emptyMap())) {
Path sourceURI = zipfs.getPath("/pathToDirectoryInsideZip/file.txt");
Path destinationURI = zipfs.getPath("/pathToDirectoryInsideZip/renamed.txt");
Files.move(sourceURI, destinationURI);
}
Using zip4j, I am modifying and re-writing the file headers inside of the central directory section to avoid rewriting the entire zip file:
ArrayList<FileHeader> FHs = (ArrayList<FileHeader>) zipFile.getFileHeaders();
FHs.get(0).setFileName("namename.mp4");
FHs.get(0).setFileNameLength("namename.mp4".getBytes("UTF-8").length);
zipFile.updateHeaders ();
//where updateHeaders is :
public void updateHeaders() throws ZipException, IOException {
checkZipModel();
if (this.zipModel == null) {
throw new ZipException("internal error: zip model is null");
}
if (Zip4jUtil.checkFileExists(file)) {
if (zipModel.isSplitArchive()) {
throw new ZipException("Zip file already exists. Zip file format does not allow updating split/spanned files");
}
}
long offset = zipModel.getEndCentralDirRecord().getOffsetOfStartOfCentralDir();
HeaderWriter headerWriter = new HeaderWriter();
SplitOutputStream splitOutputStream = new SplitOutputStream(new File(zipModel.getZipFile()), -1);
splitOutputStream.seek(offset);
headerWriter.finalizeZipFile(zipModel, splitOutputStream);
splitOutputStream.close();
}
The name field in the local file header section remains unchanged, so there will be a mismatch exception in this library.
It's tricky but maybe problematic, I don't know..

Where to put a file to read from a class under a package in java?

I have a properties file contains the file name only say file=fileName.dat. I've put the properties file under the class path and could read the file name(file.dat) properly from it in the mainClass. After reading the file name I passed the file name(just name not the path) to another class under a package say pack.myClass to read that file. But the problem is pack.myClass could not get the file path properly. I've put the file fileName.dat both inside and outside the packagepack but couldn't make it work.
Can anybody suggest me that where to put the file fileName.dat so I can read it properly and the whole application would be portable too.
Thanks!
The code I'm using to read the config file and getting the file name:
Properties prop = new Properties();
InputStream in = mainClass.class.getResourceAsStream("config.properties");
prop.load(in);
in.close();
myClass mc = new myClass();
mc.readTheFile(prop.getProperty("file"));
/*until this code is working good*/
Then in myClass which is under package named pack I am doing:
public void readTheFile(String filename) throws IOException {
FileReader fileReader = new FileReader(filename); /*this couldn't get the file whether i'm putting the file inside or outside the package folder */
/*after reading the file I've to do the BufferReader for further operation*/
BufferedReader bufferedReader = new BufferedReader(fileReader);
I assume that you are trying to read properties file using getResource method of class. If you put properties file on root of the classpath you should prefix file name with '/' to indicate root of classpath, for example getResource("/file.dat"). If properties file is under the same folder with the class you on which you invoke getResource method, than you should not use '/' prefix.
When you use a relative file name such as fileName.dat, you're asking for a file with this name in the current directory. The current directory has nothing to do with packages. It's the directory from which the JVM is started.
So if you're in the directory c:\foo\bar when you launch your application (using java -cp ... pack.MyClass), it will look for the file c:\foo\bar\fileName.dat.
Try..
myClass mc = new myClass();
InputStream in = mc.getClass().getResourceAsStream("/pack/config.properties");
..or simply
InputStream in = mc.getClass().getResourceAsStream("config.properties");
..for the last line if the main is in myClass The class loader available in the main() will often be the bootstrap class-loader, as opposed to the class-loader intended for application resources.
Class.getResource will look in your package directory for a file of the specified name.
JavaDocs here
Or getResourceAsStream is sometimes more convenient as you probably want to read the contents of the resource.
Most of the time it would be best to look for the "fileName.dat" somewhere in the "user.home" folder, which is a system property. First create a File path from the "user.home" and then try to find the file there. This is a bit of a guess as you don't provide the exact user of the application, but this would be the most common place.
You are currently reading from the current folder which is determined by
String currentDir = new File(".").getAbsolutePath();
or
System.getProperty("user.dir")
To read a file, even from within a jar archive:
readTheFile(String package, String filename) throws MalformedURLException, IOException
{
String filepath = package+"/"+filename;
// like "pack/fileName.dat" or "fileName.dat"
String s = (new SourceBase()).getSourceBase() + filepath;
URL url = new URL(s);
InputStream ins = url.openStream();
BufferedReader rdr = new BufferedReader(new InputStreamReader(ins, "utf8"));
do {
s = rdr.readLine();
if(s!= null) System.out.println(s);
}
while(s!=null);
rdr.close();
}
with
class SourceBase
{
public String getSourceBase()
{
String cn = this.getClass().getName().replace('.', '/') + ".class";
// like "packagex/SourceBase.class"
String s = this.getClass().getResource('/' + cn).toExternalForm();
// like "file:/javadir/Projects/projectX/build/classes/packagex/SourceBase.class"
// or "jar:file:/opt/java/PROJECTS/testProject/dist/
// testProject.jar!/px/SourceBase.class"
return s.substring(0, s.lastIndexOf(cn));
// like "file:/javadir/Projects/projectX/build/classes/"
// or "jar:file:/opt/java/PROJECTS/testProject/dist/testProject.jar!/"
}
}

Categories