我尝试使用Java的JTar将目录转换为tar文件,其中包含一个空的子目录和一些带有.json文件的子目录。包含文件的文件夹自动包含在.tar文件中,但空文件夹不是。我想创建包含所有(空和数据init)子目录的.tar文件。 我的代码是这样的:
try
{
File tarFile = new File("somefilename.tar");
TarOutputStream tos = new TarOutputStream(new FileOutputStream(tarFile));
tartar("directoryname", tos);
tos.close();
}
catch (Exception e)
{
e.printStackTrace();
}
private static void tartar(String dir, TarOutputStream tos)
{
File f = new File(dir);
String[] flist = f.list();
int buffersize = 1024;
byte[] buf = new byte[buffersize];
for (int i = 0; i < flist.length; i++)
{
File f2 = new File(f, flist[i]);
if (f2.isDirectory())
{
tartar(f2.getPath(), tos);
continue;
}
try
{
FileInputStream fis = new FileInputStream(f2);
// TarEntry te = new TarEntry(f2.getPath());
TarEntry te = new TarEntry(f2, f2.getPath());
tos.putNextEntry(te);
int count = 0;
while ((count = fis.read(buf, 0, buffersize)) != -1)
{
tos.write(buf, 0, count);
}
// tos.closeEntry();
// tos.close();
fis.close();
}
catch (FileNotFoundException e)
{
e.printStackTrace();
}
catch (IOException e)
{
e.printStackTrace();
}
}
}
答案 0 :(得分:0)
虽然我没有在Java中调用tarball,但在Linux中你可以使用Runtime,Process和ProcessBuilder API运行命令“tar -cvzf file_name.tar.gz directory_name /”。