src/ file path not found - java

I want to save a serializable object into the src/ folder.
File file = new File("src/test.ser");
file.createNewFile();
fout = new FileOutputStream(file);
oos = new ObjectOutputStream(fout);
oos.writeObject(object);
However, The system cannot find the path specified error messege pops up. The method works if I use an absolute file path though.
If this is in any way relevant, I've added another project into the build path.

Use ./ before src.
File file = new File("./src/test.ser");
file.createNewFile();
fout = new FileOutputStream(file);
oos = new ObjectOutputStream(fout);
oos.writeObject(object);

Related

How to download a xml file using java which is opened in browser?

I am using java and vaadin 14 as a framework. I created a xml file. It created successfully and shown in browser. But it cannot be downloaded automatically. I have a code below for creating and downloading that file. Why it doesn't work?
Creating new file code-
//Creating a xml file
String xmlOutPath,fname;
Random r = new Random();
fname = r.nextInt(1000000)+".xml"
File file = File.createTempFile("a-", fname, new File(xmlOutPath));
FileOutputStream fos = new FileOutputStream(file);
DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder docBuilder = docFactory.newDocumentBuilder();
This file successfully created. Then i have a code to download it-
import com.vaadin.flow.component.UI;
//download xml file
File downloadFile;
DOMSource source = new DOMSource(doc);
StreamResult result = new StreamResult(file);
transformer.transform(source, result);
fos.close();
downloadFile = file;
UI.getCurrent().getPage().executeJs("location.href = \"./rpttmp/" + downloadFile.getName() + ";\"");
But i found like this-
https://www.w3schools.com/xml/note.xml
How can this file automatically downloaded, rather showing that file on browser?

Edit iText PDF Java

I've been trying to load a PDF file located at "/resources/pdf/". I want to load the pdf, fill the form fields and return a stream. This is working so far, there are no errors or exceptions.
The problem is that when the resulting PDF is printed parts of the document is missing. Using this pdf, it is just printing the form fields, but not the images or the text. The code is running in a tomcat7 in combination with primefaces:
public StreamedContent modify() {
String pdfFile = "mypdf.pdf";
ByteArrayOutputStream bos = new ByteArrayOutputStream();
try {
InputStream istream = getClass().getResourceAsStream("/pdf/" + pdfFile);
PdfReader reader = new PdfReader(istream);
pdfStamper = new PdfStamper(reader, bos );
pdfForm = pdfStamper.getAcroFields();
// fillData();
pdfStamper.close();
reader.close();
istream.close();
ByteArrayInputStream bis = new ByteArrayInputStream(bos.toByteArray());
bis.close();
bos.close();
return new DefaultStreamedContent( bis, "application/pdf", "report.pdf" );
} catch (Exception ex) {
ex.printStackTrace();
return null;
}
I do build project this way: mvn clean install tomcat7:redeploy -DskipTests
Any idea what is wrong? Thanks.
I have finally decided to do it in another way.
In the project properties file I have added a new property with the path where the PDF is located, in this way I can load the pdfReader object with File through the new FileInputStream
Final code
public StreamedContent modify() {
File file = getPdfFile();
PdfReader reader = new PdfReader(new FileInputStream(file));
pdfStamper = new PdfStamper(reader, bos );
// fillData();
pdfStamper.close();
bos.close();
ByteArrayInputStream bis = new ByteArrayInputStream(bos.toByteArray());
return new DefaultStreamedContent( bis, "application/pdf", "report.pdf" );
}
public File getPdfFile() {
try {
Properties prop = new Properties();
prop.load(getClass().getClassLoader()
.getResourceAsStream("myfile.properties"));
String pdfPath = prop.getProperty("pdf.path");
String pdfName = prop.getProperty("pdf.name");
File file = new File(pdfPath + pdfName);
return file;
} catch (Exception ex) {
LOGGER.error("ERROR: " + ex.getMessage());
return null;
}
}
Thank you very much!
Regards,
Update:
I just experienced the same problem! After intensive research I detected that maven broke the encoding of my PDF files. I should have more carefully read MKLs comment ;-)
I added the resource plugin to my maven project:
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-resources-plugin</artifactId>
<version>3.1.0</version>
<configuration>
<nonFilteredFileExtensions>
<!-- Please note that images like jpg, jpeg, gif, bmp and png are (already) implicitly excluded -->
<nonFilteredFileExtension>pdf</nonFilteredFileExtension>
</nonFilteredFileExtensions>
</configuration>
</plugin>
Old post:
Your post lacks vital information:
How do you print your report.pdf? From the webbrowser or Adobe Reader? Please post the report.pdf so we can analyze.
What I understand is, that the code you posted works fine (no error, no exception). The problem occurs only at printing?
One shot what might be wrong:
You do not set the encoding (e.g. UTF-8) for your stream:
return new DefaultStreamedContent( bis, "application/pdf", "report.pdf", "YourEncoding");
and by the way the original PDF is buggy, too (E.g. Preflight reports serveral errors.)

Java application saves image on project folder instead of eclipse folder

I'm trying to save an image file to my project folder.
Image file comes from database.
It is a maven project and rest web service.
I don't have any servlets.
Here is my code, but it saves on eclipse folder.
byte[] imgData = null;
Blob img = null;
img = resultset.getBlob("LOGO");
imgData = img.getBytes(1, (int) img.length());
BufferedImage img2 = null;
img2 = ImageIO.read(new ByteArrayInputStream(imgData));
File outputfile = new File("birimler/"+resultset.getString("BASLIK")
+ "Logo.png");
outputfile.mkdirs();
ImageIO.write(img2, "png", outputfile);
System.out.println(outputfile.getAbsolutePath());
Output is: /Users/xxx/Documents/eclipse/Eclipse.app/Contents/MacOS/birimler/imageLogo.png
Thanks for help!
Thats because eclipse working dir is his installation folder.
Provide a full absolute path, or change the working dir of your run configuration.
File outputfile = new File("/birimler/"+resultset.getString("BASLIK")
+ "Logo.png");
Would end up in
"/birimler/imageLogo.png"
And adding one more slash:
File outputfile = new File("/birimler/"+resultset.getString("BASLIK")
+ "/Logo.png");
would produce:
"/birimler/image/Logo.png"

Create a .zip file in Java with images

I'm creating a Java program which gets images from a JFileChooser and create a .zip file containing the selected images. I get the files with this code:
final JFileChooser fc = new JFileChooser();
fc.setMultiSelectionEnabled(true);
fc.setFileFilter(new FileNameExtensionFilter("Image files", "bmp", "png", "jpg"));
fc.setAcceptAllFileFilterUsed(false);
fc.showOpenDialog(null);
File files[] = fc.getSelectedFiles();
How i create a .zip file containing the files of the files[] array?
Thank you for your help :D.
File someFile = new File("someFile.zip");
File files[] = fc.getSelectedFiles();
BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(someFile));
// Create the ZIP file first
try (ZipOutputStream out = new ZipOutputStream(bos)) {
// Write files/copy to archive
for (File file : files) {
// Put a new ZIP entry to output stream for every file
out.putNextEntry(new ZipEntry(file.getName()));
Files.copy(file.toPath(), out);
out.closeEntry();
}
}

Drawing a resource image on to a buffered image

Okay, I want to create a copy of an image I have in my resource folder, and put it onto the desktop pretty much. Example: My project has a resource folder with an image called apple.png. Since when I export my jar file it can't find it, I want to copy it to the desktop so it can find it from there. Here is what I tried doing:
try {
// retrieve image
BufferedImage bi = new BufferedImage(256, 256,
BufferedImage.TYPE_INT_RGB);
File outputfile = new File(
"C:/Users/Owner/Desktop/saved.png");
ImageIO.write(bi, "png", outputfile);
} catch (IOException e) {
}
}
This just created the buffered Image for me on my desktop. How do I take my res Image and copy it to it.
Any reason for loading it as an image? If you just want to copy resource to desktop without changing it:
InputStream resStream = getClass().getResourceAsStream("/image.png"));
//Improved creation of output path:
File path = new File(new File(System.getProperty("user.home")), "Desktop");
File outputFile = new File(path, "saved.png");
//now write it
Files.copy(resStream, outputFile);
You need to load the BufferedImage as the image file.
BufferedImage bi = ImageIO.read(new File(getClass().getResource("/apple.png"));));
All the other steps are the same.

Categories

Resources