我需要通过此代码提取tar文件。 但是当我使用FileOutputStream(outputFile);
时,这是错误的 " java.io.FileNotFoundException: D:\TestFile\1.png (Access is denied)"
输入是Drive D:/ testFile中的1.tar文件 并提取到同一个文件夹
我尝试通过outputFile.getCanonicalFile检查outputfile的路径,但是没关系!! 怎么了?
public class DecompressTarFile {
public ArrayList<File> getTarFileExtracted() {
return tarFileExtracted;
}
public ArrayList<File> tarFileExtracted = new ArrayList<File>();
public DecompressTarFile(File inputFile, File outputDir) throws FileNotFoundException, ArchiveException, IOException {
System.out.println("Untaring " + inputFile.getAbsolutePath() + " to dir " + outputDir.getAbsolutePath() + ".");
InputStream inputStream = new FileInputStream(inputFile);
TarArchiveInputStream tarStream = (TarArchiveInputStream) new ArchiveStreamFactory().createArchiveInputStream("tar", inputStream);
TarArchiveEntry tarEntry = null;
while ((tarEntry = (TarArchiveEntry) tarStream.getNextEntry()) != null) {
File outputFile = new File(outputDir, tarEntry.getName());
System.out.println("Attempting to write output directory " + outputFile.getAbsolutePath());
if (!outputFile.exists()) {
System.out.println("Attempting to create output directory " + outputFile.getAbsolutePath());
if (!outputFile.mkdirs()) {
throw new IllegalStateException(String.format("Couldn't create directory %s.", outputFile.getAbsolutePath()));
}
} else {
System.out.println("Create output file " + outputFile.getAbsolutePath());
OutputStream outputFileStream = new FileOutputStream(outputFile);
IOUtils.copy(tarStream, outputFileStream);
outputFileStream.close();
}
tarFileExtracted.add(outputFile);
}
tarStream.close();
}
}
并由主类
调用 static File tarFileInput = new File("D:/TestFile/haha.tar");
static File tarPathFileOutput = new File("D:/TestFile");
public static void main(String[] args) throws ArchiveException, IOException {
decomp = new DecompressTarFile(tarFileInput, tarPathFileOutput);
//listOutput = decomp.getTarFileExtracted();
}
此代码的结果
run:
Untaring D:\TestFile\haha.tar to dir D:\TestFile.
Attempting to write output directory D:\TestFile\1.png
Create output file D:\TestFile\1.png
Exception in thread "main" java.io.FileNotFoundException: D:\TestFile\1.png (Access is denied)
at java.io.FileOutputStream.open(Native Method)
at java.io.FileOutputStream.<init>(FileOutputStream.java:221)
at java.io.FileOutputStream.<init>(FileOutputStream.java:171)
at com.service..TarFile.DecompressTarFile.<init>(DecompressTarFile.java:53)
at com.service..TarFile.MainForTest.main(MainForTest.java:28)
Java结果:1
答案 0 :(得分:1)
这是问题所在:
Attempting to write output directory D:\TestFile\1.png
您已将目标文件名创建为目录。你需要分离出我需要存在的目录&#34;和&#34;我要写的文件&#34;。例如:
File outputFile = new File(outputDir, tarEntry.getName());
File outputDirectory = outputFile.getParent();
if (!outputDirectory.exists()) {
// Try to create the directory
}
哦,而且你还有一个循环条件:
while (tarEntry != null)
...但您并未在循环中更改tarEntry
的值...