I am using jtar-1.1 to try extract files from a tar file, im using the following code to try extract the files
String tarFile = "c:/test/test.tar";
String destFolder = "c:/test/myfiles";
// Create a TarInputStream
TarInputStream tis = new TarInputStream(new BufferedInputStream(new FileInputStream(tarFile)));
while (( entry = tis.getNextEntry() ) != null) {
System.out.println( "Extracting: " + entry.getName() );
int count;
byte data[] = new byte[BUFFER];
if (entry.isDirectory()) {
new File( destFolder + "/" + entry.getName() ).mkdirs();
continue;
} else {
int di = entry.getName().lastIndexOf( '/' );
if (di != -1) {
new File( destFolder + "/" + entry.getName().substring( 0, di ) ).mkdirs();
}
}
FileOutputStream fos = new FileOutputStream( destFolder + "/" + entry.getName() );
BufferedOutputStream dest = new BufferedOutputStream( fos );
while (( count = tis.read( data ) ) != -1) {
dest.write( data, 0, count );
}
dest.flush();
dest.close();
}
}
EDIT:
I have edited the code above to check is the entry a directory and once i done this it got rid of the FileNotFound error... the above code now works
I think you need to create the path before opening the FileOutputStream.
Similar Thread Here
Just off the cuff, perhaps the issue is that the entry you are receiving contains a subfolder that hasn't been created yet: 'LAB3'? In this case the directory 'LAB3' doesn't exist in the file system because you haven't created it and the file 'sg5' intends to be placed there so when you try to create a file on the fully qualified path that includes LAB3 it complains.
Related
I want to upload a file from a struts action. I need in that action the path for my folder:
I tried using
String contextPath = request.getContextPath();
but I'm getting java.lang.NullPointerException
Either store in Catalina which is parent folder to your project folder
String rootPath = System.getProperty("catalina.home");
File dir = new File(rootPath + File.separator + "yourfolderName");
if (!dir.exists())
dir.mkdirs();
// Create the file on server
java.util.Date date= new java.util.Date();
String Path = dir.getAbsolutePath() + File.separator + (new Timestamp(date.getTime())).toString().replace(":", "").toString().replace(".", ".").toString().replace(" ","").toString().replace("-","").toString()+".pdf";
Or make a folder in your project and store there.
if (!file.isEmpty()) {
//filter for checking file extewnsion
if(file.getContentType().equalsIgnoreCase("image/jpg") || file.getContentType().equalsIgnoreCase("image/jpeg")){
//if file is >2 MB or < 2MB
double size = file.getSize();
double kilobytes = (size / 1024);
double megabytes = (kilobytes / 1024);
if(megabytes<2){
try {
byte[] bytes = file.getBytes();
String filePath = request.getRealPath("/")+"yourFolderName\\ProfileImages\\"+SessionManagement.getUserName()+".jpg";
BufferedOutputStream stream =
new BufferedOutputStream(new FileOutputStream(new File(filePath)));
stream.write(bytes);
stream.close();
//console call
}
else{
model.put("error", "Please select File less than 2 MB");
return new ModelAndView("uploadPhotoTile");
}
}else{
model.put("error", "Please select JPEG File");
return new ModelAndView("uploadPhotoTile");
}
} else {
model.put("error", "Please select File");
return new ModelAndView("uploadPhotoTile");
}
Scenario: Uncompress a tar file using Apache commons.
Problem: The tar i am using is a build tar which gets deployed into a web server. This tar contains duplicate entries like below.
appender_class.xml
APPENDER_CLASS.xml
when extracting using the below code only appender_class.xml is extracted but i want both the files how can i do that ? Renaming in fly is fine but how can i accomplish that?
public static void untar(File[] files) throws Exception {
String path = files[0].toString();
File tarPath = new File(path);
TarEntry entry;
TarInputStream inputStream = null;
FileOutputStream outputStream = null;
try {
inputStream = new TarInputStream(new FileInputStream(tarPath));
while (null != (entry = inputStream.getNextEntry())) {
int bytesRead;
System.out.println("tarpath:" + tarPath.getName());
System.out.println("Entry:" + entry.getName());
String pathWithoutName = path.substring(0, path.indexOf(tarPath.getName()));
System.out.println("pathname:" + pathWithoutName);
if (entry.isDirectory()) {
File directory = new File(pathWithoutName + entry.getName());
directory.mkdir();
continue;
}
byte[] buffer = new byte[1024];
outputStream = new FileOutputStream(pathWithoutName + entry.getName());
while ((bytesRead = inputStream.read(buffer, 0, 1024)) > -1) {
outputStream.write(buffer, 0, bytesRead);
}
System.out.println("Extracted " + entry.getName());
}
}
Try opening your FileOutputstream like this instead:
File outputFile = new File(pathWithoutName + entry.getName());
for(int i = 2; outputFile.exists(); i++) {
outputFile = new File(pathWithoutName + entry.getName() + i);
}
outputStream = new FileOutputStream(outputFile);
It should generate a file called APPENDER_CLASS.xml2 if it encounters a previously created file called APPENDER_CLASS.xml. If a APPENDER_CLASS.xml2 exists it will create a APPENDER_CLASS.xml3, ad infinitum.
File.exists() takes case sensitivity into account (windows filenames are case insensitive, whereas unix, linux and mac are case sensitive). Thus with the above code on case insensitive filesystems the file would be renamed and on case sensitive filesystems the file would not be renamed.
I have to edit the html files of epubs programmatically so what I did was to unzip the .epub and create a parser to make the necessary edits for the html files. However, when I convert them back into an .epub using my code, EpubChecker shows that:
Error: Required META-INF/container.xml resource is missing
When I uncompressed my edited .epub, the container.xml is present and is not missing.
I understand that the mimetype and META-INF has to be zipped first. Here is my code to convert the files back to epub:
FileOutputStream fos = new FileOutputStream(zipFile);
ZipOutputStream zos = new ZipOutputStream(fos);
System.out.println("Output to Zip : " + zipFile);
writeMimeType(zos);
ZipEntry container = new ZipEntry("META-INF\\container.xml");
zos.putNextEntry(container);
FileInputStream inMime2 = new FileInputStream(SOURCE_FOLDER + File.separator + "META-INF\\container.xml");
int len2;
while((len2 = inMime2.read(buffer)) > 0){
zos.write(buffer, 0, len2);
}
inMime2.close();
for(String file : this.fileList){
if(!file.toString().equals("mimetype") && !file.toString().equals("META-INF\\container.xml")){
System.out.println("File Added : " + file);
ZipEntry ze= new ZipEntry(file);
zos.putNextEntry(ze);
FileInputStream in =
new FileInputStream(SOURCE_FOLDER + File.separator + file);
int len;
while ((len = in.read(buffer)) > 0) {
zos.write(buffer, 0, len);
}
in.close();
}
}
zos.closeEntry();
zos.close();
When I manually zip the directory using WinRar, no errors are seen and it works properly. I don't know what I am doing wrong. Can somebody please help me?Thank you.
Looks like you're on Windows, so your FileInputStream(SOURCE_FOLDER + File.separator + "META-INF\\container.xml"); statement is correct for the OS, but I'd guess you need to change the other 2 strings to use the forward slash for the zipentry path.
ZipEntry container = new ZipEntry("META-INF\\container.xml");
try instead as
ZipEntry container = new ZipEntry("META-INF/container.xml");
and change
if(!file.toString().equals("mimetype") && !file.toString().equals("META-INF\\container.xml")){
to
if(!file.toString().equals("mimetype") && !file.toString().equals("META-INF/container.xml")){
accordingly.
You may need to adjust your other ZipEntry's as well. From the ZIP spec (section "4.4.17 file name"):
All slashes MUST be forward slashes '/' as opposed to backwards
slashes '\'
I made an application on Android and this application logs the activity into files. I have an option to export the files so I save the files in a .zip. If there is more than 1 file to add to the .zip, I get the following error.
(general purpose flags - local: 808 hex central: 8 hex).
Local and central GPFlags values don't match.
This only happens with Android 2.3 and using winzip or 7zip. I can bypass this problem using windows explorer or winrar but I would like to solve the problem and not avoid it.
It does not happen using the same application on an Android 2.2 device.
I searched around around and found some comments about encrypting but I am not encrypting anything. I also found some comments on updating certain libraries and such but I'm using Android sdk 11 and java jdk 1.6.0_25.
I tried 2 different codes with the same result
int count = log_.getLogFileList(files_);
if (count > 0)
{
String inFileName;
File inFile;
String phoneNumLast =OsmoService.getAccountString(OsmoService.context).substring(6);
long date = files_.get(count - 1).lastModified();
SimpleDateFormat formatter = new SimpleDateFormat("MMddHHmmss");
String outdt = new String(formatter.format(new Date(date)));
String outFileName = new String("Dir Name" + "//" + "PREFIX" + "_" + outdt + ZIP_SUFFIX);
File outFile = new File(outFileName);
ZipOutputStream zos = new ZipOutputStream( new FileOutputStream( outFile ) );
BufferedOutputStream outBS = new BufferedOutputStream(zos, 8192 );
for (int idx = (count - 1); (idx >= 0) && !isCancelled(); idx--)
{
inFile = files_.get(idx);
BufferedReader inBR = new BufferedReader(new FileReader(inFile), 8192);
inFileName = inFile.getName();
Log.v(LOG_TAG, "MailLogFiles - Zipping " + inFileName);
zos.putNextEntry( new ZipEntry(inFileName));
int zix;
while ( (zix = inBR.read()) != -1 )
outBS.write(zix);
outBS.flush();
zos.closeEntry();
inBR.close();
}
outBS.close();
and this
public static void compressFileList( String[] inFiles, String outFile )
throws IOException
{
ZipOutputStream zos = new ZipOutputStream(
new BufferedOutputStream( new FileOutputStream( outFile ) ));
byte data[] = new byte[2048];
for (int i = 0; i < inFiles.length; i++)
{
BufferedInputStream in = new BufferedInputStream( new FileInputStream( inFiles[i] ) );
zos.putNextEntry( new ZipEntry(inFiles[i]) );
int count;
while( ( count = in.read( data, 0, data.length ) ) != -1 )
zos.write(data, 0, count);
zos.closeEntry();
in.close();
}
zos.close();
}
I think this is caused by a reported bug that will be fixed in Ice Cream Sandwich:
http://code.google.com/p/android/issues/detail?id=20214
I'm using this script on WINDOWS
public void copyFile(File sourceDirectory, File targetFile, File targetDirectory) throws IOException{
String temp = targetFile.getAbsolutePath();
String relativeD = temp.substring(sourceDirectory.getAbsolutePath().length(), targetFile.getAbsolutePath().length());
String rootD = sourceDirectory.getName();
String fullPath = targetDirectory.getAbsolutePath() + rootD + relativeD;
File fP = new File( fullPath );
System.out.println("PATH: " + fullPath);
FileChannel inChannel = new FileInputStream(targetFile).getChannel();
FileChannel outChannel = new FileOutputStream( fP ).getChannel();
int maxCount = (64 * 1024 * 1024) - (32 * 1024);
long size = inChannel.size();
long position = 0;
while (position < size) {
position += inChannel.transferTo(position, maxCount, outChannel);
}
if (inChannel != null) inChannel.close();
if (outChannel != null) outChannel.close();
}
What I'm doing is simple. I need to copy a file from a location to another but I have to keep the directories they're in.
So with relativeD I'm taking something like this: dir/files.sql or simply files.sql.
This is happening because for specific directories I need to copy them recursively respecting the tree structure.
The problem is this method is not working. I don't know why because if I use a simple
FileChannel outChannel = new FileOutputStream( new File( targetDirectory, targetFile ) ).getChannel();
it works. I suppose this is happening because in this case it's copying the file under an existing directory.
According to this article (top Google search hit for 'java mkdir recursive'):
Have a look at the java.io.File : it does the job perfectly, with the mkdirs function :
new File("c:/aaa/bbb/ccc/ddd").mkdirs();