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.
Related
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.
I have a method that creates a png file and then writes an image to it, however, this method works when I run the project in the IDE and fails to execute it .war, probably because of the file path.
I tried several ways that I found searching but did not succeed. Is there a way to create this png file in the resource folder so that it works in the IDE and .war?
My code that does not work in .war:
public File createPng(String name) throws Exception {
String signatureName = "signature"+name+".png";
File result = new File("src/main/resources/static/signature/"+ signatureName);
result.createNewFile();
ImageIO.write(bfImagem, "png", result);
return result;
}
I did as suggested and I used temp file and it worked.
The code looks like this:
public File createPng(String name) throws Exception {
String nameFile = "file_"+name.trim();
String suffix = "png";
result = File.createTempFile(nameFile, suffix);
ImageIO.write(bfImagem, "png", result);
return result;
}
#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.
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..
There are a lot of topics on this problem, but not one seems to have the answer I am looking for. I am attempting to open a file for read/write, but I get the file not found exception. I specified the absolute path, but to no avail. When I check "exists" and "canread" both return false. I have tried multiple files, and the result is always false. Someone mentioned it could be a permission issue, but I don't know how to fix that. Once more, if "exists" returns false, I doubt its just permission issues. Any help would be appreciated.
File myfile = new File("C:\\Users\\Eric\\workspace\\ReadJPG\\test.txt");
//File myfile = new File("C:/Users/Eric/workspace/ReadJPG/test.txt");
boolean h = myfile.canRead();
boolean p = myfile.exists();
try {
FileInputStream fis = new FileInputStream(myfile);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
Check the path. The format you're using works. I tried to replicate, but could only by miswriting the file name. My code:
import java.io.File;
public class Main {
public static void main(String[] args) {
File myfile = new File("C:\\Users\\iajrz\\Desktop\\usepass.txt");
System.out.println(myfile.exists());
}
}
prints true. Even if you had permission issues, "exists()" should return true if the file exists. Permissions wouldn't let you read, or write; they wouldn't forbid you from knowing that the file exists (i.e. listing). I tried.