I have a .tar.gz file and I want to untar that same file.
To do that I have this function in java:
private void unTarFile(String tarFile, File destFile) {
TarArchiveInputStream tis = null;
FileInputStream fis = null;
GZIPInputStream gzipInputStream = null;
BufferedInputStream bis = null;
try {
fis = new FileInputStream(tarFile);
bis = new BufferedInputStream(fis);
// .gz
gzipInputStream = new GZIPInputStream(bis);
// .tar.gz
tis = new TarArchiveInputStream(gzipInputStream);
TarArchiveEntry tarEntry = null;
while ((tarEntry = tis.getNextTarEntry()) != null) {
System.out.println(" tar entry- " + tarEntry.getName());
if (tarEntry.isDirectory()) {
continue;
} else {
// In case entry is for file ensure parent directory is in place
// and write file content to Output Stream
File outputFile = new File(destFile + File.separator + tarEntry.getName());
outputFile.getParentFile().mkdirs();
IOUtils.copy(tis, new FileOutputStream(outputFile));
}
}
} catch (IOException ex) {
System.out.println("Error while untarring a file- " + ex.getMessage());
} finally {
if (bis != null) {
try {
bis.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if (gzipInputStream != null) {
try {
gzipInputStream.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if (fis != null) {
try {
fis.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if (tis != null) {
try {
tis.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
This works and I can untar my .tar.gz successfully.
I can edit the files of the untarred directory to, but when I try to delete my directory I cant:
Did I forgot to close something?
Related
I have tried all the possible way and I have searched a lot. Only solution I found is here Adding (and overriding) files to compressed archive but when I run the code in the line zipFile.renameTo(tempFile) something happens and its just hang in there. I couldn't figure out what happened?
Can anyone help me?
File zipFile = new File("C:/ass.zip");
// get a temp file
File tempFile = null;
try {
tempFile = File.createTempFile(zipFile.getName(), null);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// delete it, otherwise you cannot rename your existing zip to it.
tempFile.delete();
System.out.println(zipFile.getAbsolutePath());
boolean renameOk=zipFile.renameTo(tempFile);
if (!renameOk)
{
try {
throw new Exception("could not rename the file "+zipFile.getAbsolutePath()+" to "+tempFile.getAbsolutePath());
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
byte[] buf = new byte[4096 * 1024];
ZipInputStream zin = null;
ZipEntry entry = null;
ZipOutputStream out = null;
try {
zin = new ZipInputStream(new FileInputStream(tempFile));
out = new ZipOutputStream(new FileOutputStream(zipFile));
entry = zin.getNextEntry();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
while (entry != null) {
String name = entry.getName();
if (entry.getName().contains("s.txt")) {
// Compress the files
InputStream in = null;
try {
in = new FileInputStream(entry.getName());
String fName = entry.getName();
// Add ZIP entry to output stream.
out.putNextEntry(new ZipEntry(fName));
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// Transfer bytes from the file to the ZIP file
int len;
try {
while ((len = in.read(buf)) > 0) {
String s = new String(buf);
if (s.contains("host=")) {
buf = s.replaceAll("host=sssws", "host="+PropertyHandler.getInstance().getProperty("hostName")).getBytes();
}
out.write(buf, 0, (len < buf.length) ? len : buf.length);
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// Complete the entry
try {
out.closeEntry();
in.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}else{
// Add ZIP entry to output stream.
try {
out.putNextEntry(new ZipEntry(name));
// Transfer bytes from the ZIP file to the output file
int len;
while ((len = zin.read(buf)) > 0) {
try {
out.write(buf, 0, len);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
try {
entry = zin.getNextEntry();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
// Close the streams
try {
zin.close();
// Complete the ZIP file
out.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
tempFile.delete();
}
you should place
tempFile.delete();
this line after rename the zipFile
boolean renameOk=zipFile.renameTo(tempFile);
so it's be like
boolean renameOk=zipFile.renameTo(tempFile);
tempFile.delete();
Yeah, so I am using this code but whenever I run it, it doesnt upload anything. I have a similar code in another program the works perfect. What have I missed?
public void upload(){
new Thread(new Runnable() {
public void run() {
if (Looper.myLooper() == null)
{
Looper.prepare();
}
FTPClient ftpClient = new FTPClient();
FileInputStream inputStream = null;
int Upload = sharedPreferences.getInt("Upload", 1);
if (Upload == 1) {
try {
ftpClient.connect(InetAddress.getByName("XXX.net"));
ftpClient.login("XXX", "XXX");
ftpClient.changeWorkingDirectory("/public_html/Images/Cross");
ftpClient.setFileType(FTP.BINARY_FILE_TYPE, FTP.BINARY_FILE_TYPE);
File file = new File(getApplicationInfo().dataDir + "/files/" + "temp" + ".jpg");
inputStream = new FileInputStream(file);
ftpClient.storeFile("temporary.jpg", inputStream);
file.delete();
ftpClient.logout();
ftpClient.disconnect();
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (SocketException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
...
}
What am I trying to do
Simulate a socialnetwork program,in which you can add your profile,change your status,your picture,add friends etc.The program must save it's content before closing in a file.
How do I intend to do it
As I can not append with ObjectOutputStream. I though of creating an ArrayList<SocialProfiles> (SocialProfiles) in this case are the profiles which I am trying to save.
I want to load the profiles from the file to the ArrayList when the program starts,and when I am done adding profiles, I want to write the profiles from the ArrayList back to the file.
I am using the size of the array as an index.Example when it first writes to the array,it writes to index 0.When it has 1 element it writes to index 1 etc etc.
What is not going as it is supposed to?
The program does not load the data from the file to the array.
What do I call at Main
try {
fileoutput = new FileOutputStream("database.dat");
} catch (FileNotFoundException e2) {
// TODO Auto-generated catch block
e2.printStackTrace();
}
try {
output = new ObjectOutputStream(fileoutput);
} catch (IOException e2) {
// TODO Auto-generated catch block
e2.printStackTrace();
}
try {
fileinput = new FileInputStream("database.dat");
} catch (FileNotFoundException e2) {
// TODO Auto-generated catch block
System.out.println("File database.dat nuk ekziston");
}
try {
input = new ObjectInputStream(fileinput);
} catch (IOException e2) {
}
loadData();
frame.addWindowListener(new WindowAdapter()
{
#Override
public void windowClosing(WindowEvent e)
{
new Thread()
{
#Override
public void run()
{
writeData();
try {
fileinput.close();
fileoutput.close();
input.close();
output.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.exit(0);
}
}.start();
}
});
Methods
public void loadData(){
try{
while (true)
{
SocialProfile temp;
temp = (SocialProfile)input.readObject();
profiles.add(profiles.size(),temp);
}
}
catch(NullPointerException e){
}
catch(EOFException e){
System.out.println("U arrit fund-i i file");
} catch (ClassNotFoundException e) {
System.out.println("Objekt-i i lexuar nuk u konvertua dot ne klasen e caktuar");
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public void writeData(){
SocialProfile temp;
for(int i=0;i<profiles.size();i++){
temp=profiles.get(i);
try {
output.writeObject(temp);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
Try to serialize/deserialize whole array instead of each object.
public void serializeData(String filename, ArrayList<SocialProfile>arrayList) {
FileOutputStream fos;
try {
fos = openFileOutput(filename, Context.MODE_PRIVATE);
ObjectOutputStream oos = new ObjectOutputStream(fos);
oos.writeObject(arrayList);
oos.flush();
oos.close();
} catch (FileNotFoundException e) {
...
}catch(IOException e){
...
}
}
private ArrayList<SocialProfile> deserializeData(String filename){
try{
FileInputStream fis = openFileInput(filename);
ObjectInputStream ois = new ObjectInputStream(fis);
return (ArrayList<SocialProfile>)ois.readObject();
} catch (FileNotFoundException e) {
...
}catch(IOException e){
...
}catch(ClassNotFoundException e){
...
}
}
The following Java code in two ways to copy files which more efficient? Want to be able to explain why, thank you.
By the way, I've tested the same file which size is about 300 megabytes. The speed of the first method as fast as the second one. But after tested more times, the result is differently.
One of my test result as below:
NO.1: Using transferFrom took 3396ms
NO.1: Using while took 3334ms
NO.2: Using transferFrom took 4239ms
NO.2: Using while took 3225ms
NO.3: Using transferFrom took 3906ms
NO.3: Using while took 4153ms
NO.4: Using transferFrom took 3100ms
NO.4: Using while took 3174ms
NO.5: Using transferFrom took 3156ms
NO.5: Using while took 3180ms
Code:
public void copyData(String inPath, String outPath1, String outPath2) {
FileChannel inChannel = null;
FileChannel outChannel = null;
FileInputStream fin = null;
FileOutputStream fout = null;
File out1File = null;
File out2File = null;
int bufferLen = 20480 * 2 * 1024;
long runTime;
ByteBuffer bb = ByteBuffer.allocateDirect(bufferLen);
for (int i = 0; i < 5; i++) {
try {
fin = new FileInputStream(new File(inPath));
out1File = new File(outPath1);
fout = new FileOutputStream(out1File);
inChannel = fin.getChannel();
outChannel = fout.getChannel();
runTime = System.currentTimeMillis();
outChannel.transferFrom(inChannel, 0, inChannel.size());
runTime = System.currentTimeMillis() - runTime;
System.out.println("NO." + (i + 1) + ": "
+ "Using transferFrom took " + runTime + "ms");
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
if (null != fin) {
try {
fin.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if (null != fout) {
try {
fout.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if (null != inChannel) {
try {
inChannel.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if (null != outChannel) {
try {
outChannel.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
out1File.deleteOnExit();
}
/**********************************************************/
try {
fin = new FileInputStream(new File(inPath));
out2File = new File(outPath2);
fout = new FileOutputStream(out2File);
inChannel = fin.getChannel();
outChannel = fout.getChannel();
runTime = System.currentTimeMillis();
while (true) {
int ret = inChannel.read(bb);
if (ret == -1) {
break;
}
bb.flip();
outChannel.write(bb);
bb.clear();
}
runTime = System.currentTimeMillis() - runTime;
System.out.println("NO." + (i + 1) + ": " + "Using while took "
+ runTime + "ms");
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
if (null != fin) {
try {
fin.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if (null != fout) {
try {
fout.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if (null != inChannel) {
try {
inChannel.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if (null != outChannel) {
try {
outChannel.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
out2File.deleteOnExit();
}
}
}
I wanted to store an Image to SD card by first converting the returned JSONObject that contains base64, then convert it to bitmap. I tried the code below, but nothing seems working.
Php code to return JSON object:
$img = $row["imageName"];
$b64img = mysql_real_escape_string($b64img);
$b64img = base64_encode ($img);
$product["imageName"] = $b64img;
Java Code that retrieves the returned JSON:
for (int i = 0; i < products.length(); i++) {
JSONObject c = products.getJSONObject(i);
byte[] decodedString = Base64.decode(c.getString(TAG_IMAGE_NAME), Base64.DEFAULT);
Bitmap decodedByte = BitmapFactory.decodeByteArray(decodedString, 0, decodedString.length);
String fileN = (i+1)+".jpg";
OutputStream fOut = null;
File file = new File(Environment.getExternalStorageDirectory() + "/FinalTestforDatabase/",fileN);
try {
fOut = new FileOutputStream(file);
} catch (FileNotFoundException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
decodedByte.compress(Bitmap.CompressFormat.JPEG, 85, fOut);
try {
fOut.flush();
} catch (IOException e2) {
// TODO Auto-generated catch block
e2.printStackTrace();
}
try {
fOut.close();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
try {
MediaStore.Images.Media.insertImage(getContentResolver(),file.getAbsolutePath(),file.getName(),file.getName());
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
I have to make sure that the main folder is created first to contain the images, then after that the code below did the trick. The next thing it to create a new folder to contains the images so "/FolderName/FolderName2/" is what I need.
OutputStream fOut = null;
File file = new File(
Environment.getExternalStorageDirectory()
+ "/FolderName/FolderName2/",
fileN);
try {
fOut = new FileOutputStream(file);
} catch (FileNotFoundException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
decodedByte.compress(
Bitmap.CompressFormat.JPEG, 85, fOut);
try {
fOut.flush();
} catch (IOException e2) {
// TODO Auto-generated catch block
e2.printStackTrace();
}
try {
fOut.close();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
try {
MediaStore.Images.Media.insertImage(
getContentResolver(),
file.getAbsolutePath(),
file.getName(), file.getName());
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}