文件以Java格式复制

时间:2011-11-16 05:46:08

标签: java jar copy file-copying

任何人都可以建议我让一个正在运行的JAR文件将自己复制到特定目录吗?

谢谢

这是我正在尝试的:

import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;

public class ahker {
  public static void main(String[] args) throws IOException {
    File inputFile = new         
File(ahker.class.getProtectionDomain().getCodeSource().getLocation().getFile());
    File outputFile = new File("C:\\TEST.jar");

    FileReader in = new FileReader(inputFile);
    FileWriter out = new FileWriter(outputFile);
    int c;

    while ((c = in.read()) != -1)
      out.write(c);

    in.close();
    out.close();
  }
}

它给了我以下编译错误:

Exception in thread "main" java.io.FileNotFoundException: 
C:\Users\---------------\bin (Access is denied)

2 个答案:

答案 0 :(得分:3)

MyClass.class.getProtectionDomain().getCodeSource().getLocation().getPath()

这是你的jar文件的路径 你可以用这个复制文件 - > http://download.oracle.com/javase/tutorial/essential/io/copy.html

Files.copy(sourcePath, targetPath, REPLACE_EXISTING);

或者这 - >

File inputFile = new File("input.txt");
File outputFile = new File("output.txt");

FileReader in = new FileReader(inputFile);
FileWriter out = new FileWriter(outputFile);
int c;

while ((c = in.read()) != -1)
  out.write(c);

in.close();
out.close();

答案 1 :(得分:1)

This solution将复制jar文件以及jar文件中的内容。

public void copyResourcesRecursively(URL originUrl, File destination) throws Exception {
    URLConnection urlConnection = originUrl.openConnection();
    if (urlConnection instanceof JarURLConnection) {
        copyJarResourcesRecursively(destination, (JarURLConnection) urlConnection);
    } else if (urlConnection instanceof FileURLConnection) {
        FileUtils.copyFilesRecusively(new File(originUrl.getPath()), destination);
    } else {
        throw new Exception("URLConnection[" + urlConnection.getClass().getSimpleName() +
                "] is not a recognized/implemented connection type.");
    }
}

public void copyJarResourcesRecursively(File destination, JarURLConnection jarConnection ) throws IOException {
    JarFile jarFile = jarConnection.getJarFile();
    for (JarEntry entry : CollectionUtils.iterable(jarFile.entries())) {
        if (entry.getName().startsWith(jarConnection.getEntryName())) {
            String fileName = StringUtils.removeStart(entry.getName(), jarConnection.getEntryName());
            if (!entry.isDirectory()) {
                InputStream entryInputStream = null;
                try {
                    entryInputStream = jarFile.getInputStream(entry);
                    FileUtils.copyStream(entryInputStream, new File(destination, fileName));
                } finally {
                    FileUtils.safeClose(entryInputStream);
                }
            } else {
                FileUtils.ensureDirectoryExists(new File(destination, fileName));
            }
        }
    }
}

Refer Here