I am trying to compress my file using the ZipOutPutStream. I tried below code and got the compressed folder with the file. But when I am extracting the folder using 7Zip, the fileName extension is missing.
Also I am unable to extract the folder by normal Extract option provided in Windows.
Below is the code I tried Using Java -8
public void compress(String compressed , String raw) {
Path pCompressed = null;
try {
pCompressed = Files.createFile(Paths.get(compressed));
try (ZipOutputStream zos = new ZipOutputStream(Files.newOutputStream(pCompressed))) {
Path pRaw = Paths.get(raw);
Files.walk(pRaw).filter(path -> !Files.isDirectory(path)).forEach(path -> {
ZipEntry zipEntry = new ZipEntry(pRaw.relativize(path).toString());
try {
zos.putNextEntry(zipEntry);
Files.copy(path, zos);
zos.closeEntry();
} catch (IOException e) {
logger.error("Exception while copying file to compressed Directory: "+e);
}
});
}
catch(IOException ioe) {
logger.error("Exception while compressing the output file: "+ioe);
}
}
catch (IOException e1) {
logger.error("Exception While Path initialization for compressing the file");
}
}
Expecting : After Extraction someFolder/MyFile.csv
I've just tried this code and when I provided it with compressed = "out.zip" and raw = "testdir", it worked fine for me. It produced a zip file containing the contents of testdir. I was then able to extract this with 7Zip and the built in Windows extraction and the files were all present and correct.
My guess is that you have not specified the .zip extension for the output file or that Windows is hiding the extension in the folder view. (I think it does this by default.)
Related
I'm having trouble fixing this issue,
I have created a Client\Server side application and created a Method where a user can
"Send" a PNG file from his side to Server side, then the Server side "Creates" and saves the image in a Package that only contains pictures.
When i run this Method of sending a Picture from Client side to Server side via Eclipse IDE
it works as expected, but when exporting Client/Server side into Runnable JAR files, i get the next error:
Java
private static void getImg(MyFile msg) {
int fileSize =msg.getSize();
System.out.println("length "+ fileSize);
try {
File newFile = new File(System.getProperty("user.dir")+"\\src\\GuiServerScreens\\"+msg.getFileName());
FileOutputStream fileOut;
fileOut = new FileOutputStream(newFile);
BufferedOutputStream bufferOut = new BufferedOutputStream(fileOut);
try {
bufferOut.write(msg.getMybytearray(), 0, msg.getSize());
fileOut.flush();
bufferOut.flush();
} catch (IOException e) {
e.printStackTrace();
}
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
I get the follow error :
java.io.FileNotFoundException: java.io.FileNotFoundException: C:\Users\Ilya\Desktop\src\GuiServerScreens\test.png (The system cannot
find the path specified)
It seems that using File newFile = new File(System.getProperty("user.dir")+"\\src\\GuiServerScreens\\"+msg.getFileName());
Does not provide the wanted result
I think you are mixing what your directories look like in netbeans with what's available on the server. Save to an external directory instead, not to your src directory.
I'm trying to compress multiple files into a single archive but with my current code, it only compresses it into a single blob inside the zip. Does anyone know how to segment the files with LZ4?
public void zipFile(File[] fileToZip, String outputFileName, boolean activeZip)
{
try (FileOutputStream fos = new FileOutputStream(new File(outputFileName), true);
LZ4FrameOutputStream lz4fos = new LZ4FrameOutputStream(fos);)
{
for (File a : fileToZip)
{
try (FileInputStream fis = new FileInputStream(a))
{
byte[] buf = new byte[bufferSizeZip];
int length;
while ((length = fis.read(buf)) > 0)
{
lz4fos.write(buf, 0, length);
}
}
}
}
catch (Exception e)
{
LOG.error("Zipping file failed ", e);
}
}
LZ4 algorithm is close with LZMA. In case you can use LZMA then you can create zip archive with LZMA compression.
List<Path> files = Collections.emptyList();
Path zip = Paths.get("lzma.zip");
ZipEntrySettings entrySettings = ZipEntrySettings.builder()
.compression(Compression.LZMA, CompressionLevel.NORMAL)
.lzmaEosMarker(true).build();
ZipSettings settings = ZipSettings.builder().entrySettingsProvider(fileName -> entrySettings).build();
ZipIt.zip(zip)
.settings(settings)
.add(files);
See details in zip4jvm
LZ4 compresses a stream of bytes. You would need to archive your multiple files into a single archive such as a Tar Archive, then feed it into the LZ4 compressor.
I created a Java library that does this for you https://github.com/spoorn/tar-lz4-java.
If you want to implement it yourself, here's a technical doc that includes details on how to LZ4 compress a directory using TarArchive from Apache Commons and lz4-java: https://github.com/spoorn/tar-lz4-java/blob/main/SUMMARY.md#lz4
I followed Where to put own properties file in an android project created with Android Studio? and I got an InputStream which reads from my .properties file successfully. However, I can't write to that .properties file, as there is no similar method to getBaseContext().getAssets().open ("app.properties") which returns an OutputStream. I have also read Java Properties File appending new values but this didn't seem to help me, my guess is my file name for the file writer is wrong but I also tried "assets\userInfo.properties" which also doesn't work.
My .properties file is in src\main\assets\userInfo.properties
Properties props = new Properties();
InputStream inputStream = null;
try{
inputStream = getBaseContext().getAssets().open("userInfo.properties");
props.load(inputStream);
props.put("name", "smith");
FileOutputStream output = new FileOutputStream("userInfo.properties"); //this line throws error
props.store(output, "This is overwrite file");
String name = props.getProperty("name");
Log.d(TAG, "onCreate: PROPERTIES TEST NAME CHANGE: " + name);
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
inputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
Current code throws this error:
java.io.FileNotFoundException: userInfo.properties (Read-only file system)
You can't write to the assets folder, as it is inside the APK which is read-only.
Use internal or external storage instead
You can't write to the assets folder. If you want to update your properties file, you'll have to put them some place else. If you want the initial version in the assets or raw folder, just copy it to the default files dir when the app is first used, then read from/write to it there.
I'm trying to download files from FTP on Java using org.apache.commons.
try {
OutputStream os = new FileOutputStream(downloadedFile);
boolean success = this.client.retrieveFile(from, os);
System.out.println("File transfer status is "+ Boolean.toString(success));
os.close();
} catch (IOException e) {
System.err.println(e.getMessage());
}
And files are downloading, but some images have error like Invalid image, another looks like that
https://www.dropbox.com/s/faozfxzag5xrk5z/Screenshot_3.png
Any ideas? Thx
Try setting file type to binary, ie:
client.setFileType(FTP.BINARY_FILE_TYPE);
FTPClient has default settings to use FTP.ASCII_FILE_TYPE.
File source=new File(fname1);
System.out.println("souce name "+fname1);
File dest = new File("F:\\BackupFiles",source.getName());
try
{
FileUtils.moveFile(source, dest);
source.delete();
}
catch (IOException ex)
{
Logger.getLogger(FileCompare.class.getName()).log(Level.SEVERE, null, ex);
}
System.out.println("file moved successfully...");
the above code throws exception
"java.io.IOException: Failed to delete original file 'C:\xampp\htdocs\eyeOS\eyeos\users\ajkani\files\html.txt' after copy to 'F:\BackupFiles\html.txt' "
and i tried to delete the file after copied it to the destination but unable to delete.
i tried deleteOnExit() method instead of delete() but nothing works.
i have used md5 algorithm to check the similarity of two files.
if the files are not same.i want to move the files to destination directory.
From above code, it seems that you want to move one file from one directory to another.
As per this assumption, you can use below code.
String sourcePath = "D:\\other\\new.xls";
File source = new File(sourcePath);
System.out.println("souce name " + sourcePath);
File destDirPath = new File("D:\\");
try {
FileUtils.moveFileToDirectory(source, destDirPath, false);
} catch (IOException e) {
e.printStackTrace();
}
System.out.println("file moved successfully...");
This will definitely help you.