RandomAccessFile throws FileNotFound exception - filenotfoundexception

I am Creating a new File using RandomAccessFile with "rw" mode. but it gives
java.io.FileNotFoundException: ../dir/test.txt (No such file or directory)
reference
This is how i created:
File baseDirAsFile = new File("../");
File dirFile = new File(baseDirAsFile, "dir");
File file = new File(dirFile, "test.txt");
RandomAccessFile raf = new RandomAccessFile(file, "rw");
Note:
It is not throwing that exception all the time. But can't identify when and why it is throwing this at some particular time.

I believe your code should be:
String baseDir = new File(".").getAbsolutePath();
String dirFile = baseDirAsFile + File.separator + "dir";
File file = new File(dirFile + File.separator + "test.txt");
RandomAccessFile file = new RandomAccessFile(file, "rw");

Related

Read file from Springboot Resources in Docker Container

I am trying to send email with inline image in the email body. The code is working fine when I am running it locally from eclipse. But when it's getting dockerized and deployed to Kubernetes cluster it's unable to read the png file.
I am getting the error "java.io.FileNotFoundException: class path resource [External_Files/email_template.png] cannot be resolved to absolute file path because it does not reside in the file system: jar:file:/app.jar!/BOOT-INF/classes!/External_Files/email_template.png"
Project structure screen shot
MimeMessage message = new MimeMessage(session);
message.setFrom(new InternetAddress(fromEmail));
message.setSubject(AppConstants.EMAIL_SUBJECT);
MimeMultipart multipart = new MimeMultipart(AppConstants.RELATED);
MimeBodyPart messageBodyPart = new MimeBodyPart();
String html = AppConstants.EMAIL_HTML_PART_1 + recepientName +
AppConstants.EMAIL_HTML_PART_2
+ fromName + AppConstants.EMAIL_HTML_PART_3 + appProperties.getEmailOnboardPage()
+ AppConstants.EMAIL_HTML_PART_4 + appProperties.getEmailHelpPage()
+ AppConstants.EMAIL_HTML_PART_5;
messageBodyPart.setContent(html, AppConstants.TEXT_HTML);
multipart.addBodyPart(messageBodyPart);
MimeBodyPart messageBodyPart2 = new MimeBodyPart();
DataSource fds = new FileDataSource(ResourceUtils.getFile(src/main/resources/External_Files/email_template.png));
messageBodyPart2.setDataHandler(new DataHandler(fds));
messageBodyPart2.setHeader(AppConstants.CONTENT_ID, AppConstants.IMAGE_HEADER);
multipart.addBodyPart(messageBodyPart2);
message.setContent(multipart);
message.setHeader(AppConstants.X_PRIORITY, AppConstants.ONE);
message.addRecipient(Message.RecipientType.TO, new InternetAddress(recipient));
log.info("executing Transport.send");
Transport.send(message);
png
#Indranil Halder I know it's late to answer but for others who have this problem finding this issue would be useful
you can use ResourceLoader to find classpath in spring jar file
#Autowired
ResourceLoader resourceLoader;
Resource resource = resourceLoader.getResource("classpath:External_Files/email_template.png");

Merging All Pdf Files in Directory Using iText

Hello everyone and thanks for your help in advance. I am trying to use iText to merge all Pdf files contained within a directory. Here is my code:
public class MergeFiles
{
public MergeFiles(string targetDirectory) {
string dest = targetDirectory + #"\Merged.pdf";
PdfDocument pdfDoc = new PdfDocument(new PdfWriter(dest));
PdfMerger merger = new PdfMerger(pdfDoc);
string[] fileEntries = Directory.GetFiles(targetDirectory);
foreach (string fileName in fileEntries) {
//PdfMerger merger = new PdfMerger(pdfDoc);
PdfDocument newDoc = new PdfDocument(new PdfReader(fileName));
merger.Merge(newDoc, 1, newDoc.GetNumberOfPages());
newDoc.Close();
};
pdfDoc.Close();
}
}
This code is resulting in the error "System.IO.IOException: The process cannot access the file 'E:\Merged.pdf' because it is being used by another process." however, I am not sure why. Any help would be appreciated.
After these two lines:
string dest = targetDirectory + #"\Merged.pdf";
PdfDocument pdfDoc = new PdfDocument(new PdfWriter(dest));
A new (empty) file with name "Merged.pdf" is created in your target directory, with file stream opened in writing mode to write the result of the merging process.
Then, you are getting the list of file in target directory with string[] fileEntries = Directory.GetFiles(targetDirectory);. This array already includes your newly created Merged.pdf file.
Eventually the code tries to merge the resultant file into itself, which obviously fails.
To avoid this error, either collect the files to merge before creating the target document (but make sure there is no existing "Merged.pdf" file in the target directory already):
string[] fileEntries = Directory.GetFiles(targetDirectory);
string dest = targetDirectory + #"\Merged.pdf";
PdfDocument pdfDoc = new PdfDocument(new PdfWriter(dest));
// The rest of the code
Or, simply remove the target file from fileEntries array manually before merging the files.

Spring cannot find the file via specified path

My files hierarchy:
>resources:
>static:
>css:
>json:
>networks:
>network-list.json
>js:
>img:
I've tried to create a new file via:
File jsonNetworkDetailsFile = new File("/json/networks/network-list.json");
File jsonNetworkDetailsFile = new File("static/json/networks/network-list.json");
File jsonNetworkDetailsFile = new File("../json/networks/network-list.json");
File jsonNetworkDetailsFile = new File("../../json/networks/network-list.json");
File jsonNetworkDetailsFile = new File("/json/networks/network-list.json");
...and some more. None of it works.
I'm still getting the
java.io.FileNotFoundException: the system cannot find the path specified
What's the proper way?
EDIT
Found a solution. Had to include full path to the file like:
File jsonNetworkDetailsFile = new File("src/main/resources/static/json/networks/Turtlecoin/turtlecoin-pools.json");
EDIT2
As TwiN stated - it's impossible to reference a file through File object as soon as the app is packed into .jar. A proper solution would include:
InputStream jsonNetworkDetailsFile = new ClassPathResource("/static/json/networks/network-list.json").getInputStream();
InputStream is = new ClassPathResource("/someFile.txt").getInputStream();
where /someFile.txt is in your resources folder.
As mentioned in the documentation for ClassPathResource:
Supports resolution as java.io.File if the class path resource resides
in the file system, but not for resources in a JAR. Always supports
resolution as URL.
In other words, you'll want to use the getInputStream() method for your case:
InputStream is = new ClassPathResource("/someFile.txt").getInputStream();
try {
String contents = new String(FileCopyUtils.copyToByteArray(is), StandardCharsets.UTF_8);
System.out.println(contents); // do something with the content here
is.close();
} catch (IOException e) {
e.printStackTrace();
}
I'm mentioning this because ClassPathResource also has a getFile() method.
For more details, see reference
Try something like this :
ClassLoader classLoader = getClass().getClassLoader();
File file = new File(classLoader.getResource("classpath:static/json/networks/network-list.json").getFile());
You could also use :
#Value(value = "static/json/networks/network-list.json")
private Resource myFile;
And then :
myFile.getInputStream()
(will only work on a class annoted with #Component, #Service... etc)
you can try this to load files from ressources :
ClassLoader loader = Thread.currentThread().
getContextClassLoader();
InputStream configStream = loader.getResourceAsStream("/static/json/networks/network-list.json");
I think you should give the exact location to File object. Another solution:
File currDir = new File(".");
String path = currDir.getAbsolutePath();
// String path = "C:\\ExternalFiles\\"; // Or you can give staticly
File jsonNetworkDetailsFile = new File(path);
Hope it helps.

Spring Boot load another file from app.properties

I am new to Spring Boot. I have this emailprop.properties in src/main/resource:
//your private key
mail.smtp.dkim.privatekey=classpath:/emailproperties/private.key.der
But I am getting the error as
classpath:\email properties\private.key.der (The filename, directory
name, or volume label syntax is incorrect)
How do I properly load this file?
Update-1
my java code is
dkimSigner = new DKIMSigner(emailProps.getProperty("mail.smtp.dkim.signingdomain"), emailProps.getProperty("mail.smtp.dkim.selector"),
emailProps.getProperty("mail.smtp.dkim.privatekey"));
its working as "D:\\WorkShop\\MyDemoProj\\EmailService\\src\\main\\resources\\private.key.der"Instead of emailProps.getProperty("mail.smtp.dkim.privatekey")
Update-2
i have tried java code is
String data = "";
ClassPathResource cpr = new ClassPathResource("private.key.der");
try {
byte[] bdata = FileCopyUtils.copyToByteArray(cpr.getInputStream());
data = new String(bdata, StandardCharsets.UTF_8);
} catch (IOException e) {
e.printStackTrace();
}
dkimSigner = new DKIMSigner(emailProps.getProperty("mail.smtp.dkim.signingdomain"), emailProps.getProperty("mail.smtp.dkim.selector"),data);
Error is : java.io.FileNotFoundException: class path resource [classpath:private.key.der] cannot be resolved to URL because it does not exist
Tried Code is :
ClassPathResource resource = new ClassPathResource(emailProps.getProperty("mail.smtp.dkim.privatekey"));
File file = resource.getFile();
String absolutePath = file.getAbsolutePath();
Still same error..
please update the answer..
If you want to load this file runtime then you need to use ResourceLoader please have a look here for the documentation - section 8.4.
Resource resource = resourceLoader.getResource("classpath:/emailproperties/private.key.der");
Now if you want to keep this exact path in properties file you can keep it there and then load it in your Autowired constructor/field like that:
#Value("${mail.smtp.dkim.privatekey}") String pathToPrivateKey
and then pass this to the resource loader.
Full example you can find here. I don't want to copy paste it.
If your file is located here:
"D:\\WorkShop\\MyDemoProj\\EmailService\\src\\main\\resources\\private.key.der"
then it should be:
mail.smtp.dkim.privatekey=classpath:private.key.der
EDIT:
I see now, you are using DKIMSigner, which expects file-path string,
Try changing your code like this:
ClassPathResource resource = new ClassPathResource(emailProps.getProperty("mail.smtp.dkim.privatekey"));
File file = resource.getFile();
String absolutePath = file.getAbsolutePath();
dkimSigner = new DKIMSigner(emailProps.getProperty("mail.smtp.dkim.signingdomain"), emailProps.getProperty("mail.smtp.dkim.selector"),absolutePath
);

Error Java.io.FileNotFoundException

In my project i read excel file. this functionality working on local host but i upload this project on server that time i get error like below
java.io.FileNotFoundException: D:/Java_Question.xls (No such file or directory)
at java.io.FileInputStream.open(Native Method)
at java.io.FileInputStream.<init>(FileInputStream.java:146)
at java.io.FileInputStream.<init>(FileInputStream.java:101)
Controller.AdminExelSheetController.read(AdminExelSheetController.jav a:190)
Why this error on server?
Read excel file code: Here where changes required ?
FileInputStream inputFile = new FileInputStream("D:/" + fileName);
POIFSFileSystem systemFile = new POIFSFileSystem(inputFile);
HSSFWorkbook wb = new HSSFWorkbook(systemFile);
HSSFSheet sheet = wb.getSheetAt(0);
Iterator rows = sheet.rowIterator();
if (!"".equals(rows.toString())) {
while (rows.hasNext()) {
HSSFRow row = (HSSFRow) rows.next();
Iterator cells = row.cellIterator();
Vector cellStore = new Vector();
while (cells.hasNext()) {
HSSFCell cell = (HSSFCell) cells.next();
cellStore.addElement(cell);
}rowStore.addElement(cellStore);}
Because your project has a different path on the server.
You should get your file path like this...
String path = ServletContext.getRealPath("/FolderInYourProjectWhereExcelIsLocated");

Resources