I zipped a directory called dir2 that contains some text files. I want to create a directory in external storage called dir that holds dir2.
Given a zipped dir2, I am trying to extract so it looks like:
external_storage_path/dir/dir2/textfile.txt
createFile(zis, "dir2/textfile.txt");
private void createFile(ZipInputStream zipIn, String filename) {
if(android.os.Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
boolean created = false;
File newFile = new File(Environment.getExternalStorageDirectory(),
"dir/dir2/textfile.txt");
if(!newFile.exists()) {
// create the file and any parent dirs if needed
created = newFile.mkdirs();
}
if(created) {
BufferedOutputStream bos = null;
try {
FileOutputStream fos = new FileOutputStream(newFile.getAbsolutePath());
bos = new BufferedOutputStream(fos);
} catch (FileNotFoundException fnf) {
fnf.printStackTrace();
}
An exception is thrown when trying to create the BufferedOutputStream:
java.io.FileNotFoundException:
/storage/emulated/0/dir/dir2/textfile.txt: open failed: EISDIR (Is a
directory)
The textfile is not a directory though.
Related
This spring app performs simple file upload,
here's the controller class
#Override
public String fileUpload(MultipartFile file) {
try{
// save uploaded image to images folder in root dir
Files.write(Paths.get("images/"+ file.getOriginalFilename()), file.getBytes());
// perform some tasks on image
return "";
} catch (IOException ioException) {
return "File upload has failed.";
} finally {
Files.delete(Paths.get("images/" + file.getOriginalFilename()));
}
}
but when i build jar and runs, it throws IOException saying,
java.nio.file.NoSuchFileException: images\8c9.jpeg.
So my question is how can i add the images folder inside the jar executable itself.
Thanks.
You should provide a full path for the images folder, or save in java.io.tmpdir creating the image folder first.
But, in my opinion you should configure your upload folder from a config file for flexibility. Take a look at this.
app:
profile-image:
upload-dir: C:\\projs\\web\\profile_image
file-types: jpg, JPG, png, PNG
width-height: 360, 360
max-size: 5242880
In your service or controller, do whatever you like, may be validate image type, size etc and process it as you like. For instance, if you want thumbnails(or avatar..).
In your controller or service class, get the directory:
#Value("${app.image-upload-dir:../images}")
private String imageUploadDir;
Finally,
public static Path uploadFileToPath(String fullFileName, String uploadDir, byte[] filecontent) throws IOException {
Path fileOut = null;
try{
Path fileAbsolutePath = Paths.get(StringUtils.join(uploadDir, File.separatorChar, fullFileName));
fileOut = Files.write(fileAbsolutePath, filecontent);
}catch (Exception e) {
throw e;
}
return fileOut; //full path of the file
}
For your question in the comment: You can use java.io.File.deleteOnExit() method, which deletes the file or directory defined by the abstract path name when the virtual machine terminates. TAKE A GOOD CARE THOUGH, it might leave some files if not handled properly.
try (ByteArrayOutputStream output = new ByteArrayOutputStream();){
URL fileUrl = new URL(url);
String tempDir = System.getProperty("java.io.tmpdir");
String path = tempDir + new Date().getTime() + ".jpg"; // note file extension
java.io.File file = new java.io.File(path);
file.deleteOnExit();
inputStream = fileUrl.openStream();
ByteStreams.copy(inputStream, output); // ByteStreams - Guava
outputStream = new FileOutputStream(file);
output.writeTo(outputStream);
outputStream.flush();
return file;
} catch (Exception e) {
throw e;
} finally {
try {
if(inputStream != null) {
inputStream.close();
}
if(outputStream != null) {
outputStream.close();
}
} catch(Exception e){
//skip
}
}
I got a FileNotFoundException#5818 when I try to get a file address using getExternalStoragePublicDirectory().
This is my method copied from Google Dev Documentation:
public File getPublicDir(String albumName) {
// Get the directory for the user's public pictures directory.
File file = new File(Environment.getExternalStoragePublicDirectory(
Environment.DIRECTORY_PICTURES), albumName);
if (!file.mkdirs()) {
Log.e("PUBLIC DIRECTORY", "Directory not created");
}
return file;
}
I call this method here:
try{
FileOutputStream fos=new FileOutputStream(getPublicDir("mySnapshot"));
Boolean success=snapshot.compress(Bitmap.CompressFormat.PNG, 100, fos);
Toast.makeText(MainActivity.this,"Compress?
:"+success,Toast.LENGTH_SHORT).show();
fos.close();
}catch(IOException e){
e.printStackTrace();
Toast.makeText(MainActivity.this,"NOT SAVED",Toast.LENGTH_SHORT).show();
}
I am not exactly sure what albumName is. Is it the name of the folder to be created or the name of the photo file to be stored?
Here is a screenshot of the error it throws when I was debugging:
It throws the error at line "FileOutputStream fos=new FileOutputStream(getPublicDir("mySnapshot"));."
Write permission added.
Here is what my app looks like (GIF), and the error it throws:
This is where I create a folder (GIF):\
I found here a way to write text into directory, it works but it's only for text:
try {
FileOutputStream fos = new FileOutputStream(myExternalFile);
fos.write(inputText.getText().toString().getBytes());
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
myExternalFile = new File(getExternalFilesDir(filepath), filename);
private String filename = "SampleFile.txt";
private String filepath = "MyFileStorage";
I try to write byte data to directory I use the following code but i get this
Exception in thread "main" java.io.FileNotFoundException: C:\file (Access is denied)
at java.io.FileOutputStream.open(Native Method)
at java.io.FileOutputStream.<init>(FileOutputStream.java:213)
at java.io.FileOutputStream.<init>(FileOutputStream.java:162)
at com.innvo.domain.App.main(App.java:17)
My code:
public static void main(String[] args) throws IOException {
File dir = new File("C:\\file");
if (dir.isDirectory())
{
String x="new text string";
File serverFile = new File(dir.getAbsolutePath());
BufferedOutputStream stream = new BufferedOutputStream(
new FileOutputStream(serverFile));
System.out.println(x.getBytes());
stream.close();
}else {
System.out.println("not");
}
}
serverFile is a directory. FileOutputStream does not accept directories.
You cannot write to a directory like to a file.
Use something like `
File serverFile = new File(dir,"mynewfile.txt");
Here i have Bookfolder in that few more folders(english,hindi,japanese).Converting english,hindi,japanese to english.zip,hindi.zip and japanese.zip.Everything is working fine and i'm keeping zip files and folders inside Bookfolder,this thing i'm doing using with java.But when i'm unzipping manually the zip file ex:english.zip ,right click on that extract here then showing error as UNEXPECTED END OF ARCHIVE.This is my code.
public void foldertToZip(File zipDeleteFile) {
//System.out.println(zipDeleteFile);
File directoryToZip = zipDeleteFile;
List<File> fileList = new ArrayList<>();
//System.out.println("---Getting references to all files in: " + directoryToZip.getCanonicalPath());
getAllFiles(directoryToZip, fileList);
//System.out.println("---Creating zip file");
writeZipFile(directoryToZip, fileList);
//System.out.println("---Done");
}
public static void getAllFiles(File dir, List<File> fileList) {
try {
File[] files = dir.listFiles();
for (File file : files) {
fileList.add(file);
if (file.isDirectory()) {
System.out.println("directory:" + file.getCanonicalPath());
getAllFiles(file, fileList);
} else {
System.out.println("file:" + file.getCanonicalPath());
}
}
} catch (IOException e) {
}
}
public static void writeZipFile(File directoryToZip, List<File> fileList) {
try {
//try (FileOutputStream fos = new FileOutputStream(directoryToZip.getName() + ".zip"); ZipOutputStream zos = new ZipOutputStream(fos)) {
File path = directoryToZip.getParentFile();
File zipFile = new File(path, directoryToZip.getName() + ".zip");
try (FileOutputStream fos = new FileOutputStream(zipFile)) {
ZipOutputStream zos = new ZipOutputStream(fos);
for (File file : fileList) {
if (!file.isDirectory()) { // we only zip files, not directories
addToZip(directoryToZip, file,zos);
}
}
}
} catch (FileNotFoundException e) {
} catch (IOException e) {
}
}
public static void addToZip(File directoryToZip, File file, ZipOutputStream zos) throws FileNotFoundException,
IOException {
try (FileInputStream fis = new FileInputStream(file)) {
String zipFilePath = file.getCanonicalPath().substring(directoryToZip.getCanonicalPath().length() + 1,
file.getCanonicalPath().length());
System.out.println("Writing '" + zipFilePath + "' to zip file");
ZipEntry zipEntry = new ZipEntry(zipFilePath);
zos.putNextEntry(zipEntry);
byte[] bytes = new byte[1024];
int length;
while ((length = fis.read(bytes)) >= 0) {
zos.write(bytes, 0, length);
}
zos.closeEntry();
}
}`
while i'm extracting new zip file(eg:english.zip) it showing error as unexpected end of archieve (i think not zipping exactly)'
You need to close ZipOutputStream in writeZipFile() method;
for (File file : fileList) {
if (!file.isDirectory()) { // we only zip files, not directories
addToZip(directoryToZip, file,zos);
}
}
//here close zos
zos.close();
I was missing media type on ResponseEntity object and therefore I got this error information during extracting zip archive.
That means when calling rest api to download zip archive with files then needed information needs to be passed within ResponseEntity (media type application/zip, header info, cache info, etc.).
Another observation
is that I was missing correct return response type from angular side. There must be responseType as blob and not as text. That caused me the main issue.
Angular side:
getZIPData(id: number) {
const path = resolveBase() + 'rest-api-path' + id
return this._http.get(path, { observe: 'response', responseType: 'blob' });
}
It might help somebody.
Here i have folder(Books)structure inside of Books folder i have folders called physics,chemistry,science,english.I'm passing Books folder as zipDeleteFile but inside all folder has to convert in the same folder(Books)as physics.zip,chemistry.zip,science.zip,english.zip.But this code is not working.
'
public void foldertToZip(File zipDeleteFile) {
//System.out.println(zipDeleteFile);
File directoryToZip = zipDeleteFile;
List<File> fileList = new ArrayList<File>();
//System.out.println("---Getting references to all files in: " + directoryToZip.getCanonicalPath());
getAllFiles(directoryToZip, fileList);
//System.out.println("---Creating zip file");
writeZipFile(directoryToZip, fileList);
//System.out.println("---Done");
}
public static void getAllFiles(File dir, List<File> fileList) {
try {
File[] files = dir.listFiles();
for (File file : files) {
fileList.add(file);
if (file.isDirectory()) {
System.out.println("directory:" + file.getCanonicalPath());
getAllFiles(file, fileList);
} else {
System.out.println(" file:" + file.getCanonicalPath());
}
}
} catch (IOException e) {
e.printStackTrace();
}
}
public static void writeZipFile(File directoryToZip, List<File> fileList) {
try {
try (FileOutputStream fos = new FileOutputStream(directoryToZip.getName() + ".zip")) {
ZipOutputStream zos = new ZipOutputStream(fos);
for (File file : fileList) {
if (!file.isDirectory()) { // we only zip files, not directories
addToZip(directoryToZip, file, zos);
}
}
zos.close();
}
} catch (FileNotFoundException e) {
} catch (IOException e) {
}
}
public static void addToZip(File directoryToZip, File file, ZipOutputStream zos) throws FileNotFoundException,
IOException {
try (FileInputStream fis = new FileInputStream(file)) {
String zipFilePath = file.getCanonicalPath().substring(directoryToZip.getCanonicalPath().length() + 1,
file.getCanonicalPath().length());
System.out.println("Writing '" + zipFilePath + "' to zip file");
ZipEntry zipEntry = new ZipEntry(zipFilePath);
zos.putNextEntry(zipEntry);
byte[] bytes = new byte[1024];
int length;
while ((length = fis.read(bytes)) >= 0) {
zos.write(bytes, 0, length);
}
zos.closeEntry();
}
}`'
Initially i'm passing zipDeleteFile as C:\Books inside Books i have all physics,english,science folder those folders has to convert into zip files in the same root folder(Books).
So, basically, you want to zip each of the directories in the Books folder into their own zip file. There is a couple of ways you could do this, but the eaiest might be to change the way you are calling foldertToZip
So, instead of (something like)...
foldertToZip(new File("C:\\Books"));
You could do something like...
for (File file : new File("C:\\Books").listFiles()) {
if (file.isDirectory()) {
foldertToZip(file);
}
}
This will result in each directory within Books been added to it's own zip file, which will reside within Books
One other change you might need to make is...
public static void writeZipFile(File directoryToZip, List<File> fileList) {
try {
//try (FileOutputStream fos = new FileOutputStream(directoryToZip.getName() + ".zip")) {
File path = directoryToZip.getParentFile();
File zipFile = new File(path, directoryToZip.getName() + ".zip");
try (FileOutputStream fos = new FileOutputStream(zipFile)) {
This will create the zip file within the parent directory of the directory to be zipped (ie, the Books directory)