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();
}
}
Related
My requirement is that there is a .xls file within a zip file, which can be downloaded using an URL. As I want to read this excel file in memory (for later processing), without downloading the zip locally, I have used ZipInputStream and this is how the main part of my code looks like:
String finalUrl = "https://server/myZip.zip"
URL url = new URL(finalUrl);
InputStream inputStream = new BufferedInputStream(url.openStream());
ZipInputStream zis = new ZipInputStream(inputStream);
ZipEntry file;
try {
while ((file = zis.getNextEntry()) != null) {
if (file.getName().endsWith(".xls")) {
log.info("xls file found");
log.info("file name : {}", file.getName());
byte excelBytes[] = new byte[(int)file.getSize()];
zis.read(excelBytes);
InputStream excelInputStream = new ByteArrayInputStream(excelBytes);
HSSFWorkbook wb = new HSSFWorkbook(excelInputStream);
HSSFSheet sheet = wb.getSheetAt(8);
log.info("sheet : {}", sheet.getSheetName());
}
else {
log.info("xls file not found");
}
}
}
finally{
zis.close();
}
But unfortunately I am receiving the following error:
java.lang.ArrayIndexOutOfBoundsException: Index -3 out of bounds for length 3247
Note:
The .xls file is around 2MB and the zip file does not have any complex structure such as sub-directories or multiple files.
Any help here would be highly appreciated. Thanks!
Thanks to #PJ Fanning for highlighting this,
The problem was in zis.read(excelBytes) which does not guarantee to read all the bytes. After using IOUtils.toByteArrayinstead, the problem was resolved. The correct code is:
String finalUrl = "https://server/myZip.zip"
URL url = new URL(finalUrl);
InputStream inputStream = new BufferedInputStream(url.openStream());
ZipInputStream zis = new ZipInputStream(inputStream);
ZipEntry file;
try {
while ((file = zis.getNextEntry()) != null) {
if (file.getName().endsWith(".xls")) {
log.info("xls file found");
log.info("file name : {}", file.getName());
byte excelBytes[] = IOUtils.toByteArray(zis);
InputStream excelInputStream = new ByteArrayInputStream(excelBytes);
HSSFWorkbook wb = new HSSFWorkbook(excelInputStream);
HSSFSheet sheet = wb.getSheetAt(8);
log.info("sheet : {}", sheet.getSheetName());
}
else {
log.info("xls file not found");
}
}
}
finally{
zis.close();
}
The absolute file path seems to be forming correctly but the file is not being written.
Code:
var image = ImageIO.read(new ByteArrayInputStream(attachPageScreenshot()));
var saveDirectory = Paths.get("target", "screenshots").toAbsolutePath().toString();
var builder = new StringBuilder();
builder.append("\\").append(context.getDisplayName()).append(".png");
var filePath = saveDirectory.concat(builder.toString());
var saveFile = new File(filePath);
ImageIO.write(image, "png", saveFile);
Output:
java.io.FileNotFoundException: E:\workspace\java\selenium-junit5-starter\target\screenshots\Verify Total Interest Per Annum - Deposit = 30000, Term = 2 Years.png (The system cannot find the path specified)
Anything amiss?
I assumed Paths.get() automatically created the directory if it did not exist.
var dir = new File(saveDirectory);
if (!dir.exists()) {
dir.mkdirs();
}
ImageIO.write(image, "png", saveFile);
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);
I am making a chat application in which user also has the option to send pictures. I want to save the images to the application folder so I can access those images to fill the chat window up with previous messages with pictures and text. So my question is how can I add an image to the application folder?
Thanks
first you have to create your app name folder into sd card then you have to write your file/image into it
String SDCardRoot = Environment.getExternalStorageDirectory().toString();
String filename = "fileName" + ".jpg";
File myDir = new File(SDCardRoot + "/AppName");
myDir.mkdirs();
File file = new File(myDir, filename);
FileOutputStream fileOutput = new FileOutputStream(file);
//write the file into the sdcard folder specify your buffer , bufferLength
fileOutput.write(buffer, 0, bufferLength);
fileOutput.close();
then only you can access the files from app folder
File imgFile;
String path = Environment.getExternalStorageDirectory() + "/AppName/" + ".jpg";
imgFile = new File(path);
if (imgFile.exists()) {
Bitmap bitmap = BitmapFactory.decodeFile(imgFile.getAbsolutePath());
imageView.setImageBitmap(bitmap);
}
I have to save an excel file with .xls extension.I want that the extension should be taken by default as soon as I select the file type in save file dialog box designed using file chooser.I have tried this much of code but it is saving the file in .xls format only when I give the file name as filename.xls
public void FileSave() throws IOException{
JFileChooser chooser=new JFileChooser(".");
FileNameExtensionFilter filter = new FileNameExtensionFilter("Excel files","xls","excel");
chooser.addChoosableFileFilter(filter);
chooser.setFileFilter(filter);
chooser.setFileSelectionMode(chooser.FILES_AND_DIRECTORIES);
chooser.setDialogTitle("Save File");
chooser.setCurrentDirectory(new File(System.getProperties().getProperty("user.home")));
chooser.setFileFilter(new javax.swing.filechooser.FileFilter(){
public boolean accept(final File f){
return f.isDirectory()|| file.getAbsolutePath().endsWith(".xls");
}
public String getDescription(){
return "Excel files (*.xls)";
}
});
int returnVal1=chooser.showSaveDialog(this);
if (returnVal1 == JFileChooser.APPROVE_OPTION){
file1 = chooser.getSelectedFile();
if(!file1.exists()){
FileOutputStream fileOut = new FileOutputStream(file1);
hwb.write(fileOut);
fileOut.close();
System.out.println("\n Your Excel file has been generated!");
JOptionPane.showMessageDialog(this,"File Created.");
}
else if(file1.exists()){
int res=JOptionPane.showConfirmDialog(this,"File already exists.Do you wish to overwrite?");
if(res == JOptionPane.YES_OPTION){
FileOutputStream fileOut = new FileOutputStream(file1);
hwb.write(fileOut);
fileOut.close();
System.out.println("\n Your Excel file has been generated!");
JOptionPane.showMessageDialog(this,"File Created.");
}else if(res == JOptionPane.NO_OPTION){
int returnVal2=chooser.showSaveDialog(this);
if (returnVal2 == JFileChooser.APPROVE_OPTION){
File file2 = chooser.getSelectedFile();
if(!file2.exists()){
FileOutputStream fileOut = new FileOutputStream(file2);
hwb.write(fileOut);
fileOut.close();
System.out.println("\n Your Excel file has been generated!");
JOptionPane.showMessageDialog(this,"File Created.");
}
}
}else if (res == JOptionPane.CANCEL_OPTION){
JOptionPane.showMessageDialog(this, "User cancelled operation.");
}
}
}
}
You need to use this option to set the file name as *.xls:
chooser.setSelectedFile("*.xls");
And for the File type dropdown, set the below options:
JFileChooser chooser = new JFileChooser();
FileNameExtensionFilter filter = new FileNameExtensionFilter("Excel files","xls","excel");
chooser.addChoosableFileFilter(filter);
chooser.setFileFilter(filter);
chooser.setAcceptAllFileFilterUsed(false);
I did this and it worked.
if(!file1.exists())
{
FileOutputStream fileOut = new FileOutputStream(file1+".xls");
hwb.write(fileOut);
fileOut.close();
System.out.println("\n Your Excel file has been generated!");
JOptionPane.showMessageDialog(this,"File Created.");
}