Java 来自internet的文件已损坏
我正在从互联网下载一个带有此代码的文件Java 来自internet的文件已损坏,java,Java,我正在从互联网下载一个带有此代码的文件 void download(String source, String destination, int size) { // ten percent of the total download size File ofile = new File(System.getProperty("user.dir") + "", destination); System.out.printf("\nDownloading\n\t%s\nTo
void download(String source, String destination, int size) {
// ten percent of the total download size
File ofile = new File(System.getProperty("user.dir") + "", destination);
System.out.printf("\nDownloading\n\t%s\nTo\n\t%s\n", source, destination);
try {
if (ofile.exists()) ofile.delete();
if (!ofile.createNewFile()) {
throw new IOException("Can't create " + ofile.getAbsolutePath());
}
int inChar = 0;
URL url = new URL(source);
InputStream input = url.openStream();
FileOutputStream fos = new FileOutputStream(ofile);
for (int i = 0; i < size && inChar != -1; i++) {
inChar = input.read();
fos.write(inChar);
}
input.close();
fos.close();
System.out.println("Downloaded " + ofile.getAbsolutePath());
} catch (EOFException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
Main frame = new Main();
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
但是,下载的jar似乎已损坏
"Error or invalid corrupt file /path/privateers.jar"
当我右键单击实际文件并点击“RunwithJava”(在程序外部)时,它也会抛出相同的错误
但是,当我直接从FTP服务器而不是从应用程序下载它时,它工作正常,没有任何损坏
我怎样才能解决这个问题
谢谢 添加最后一行:
final Process process = Runtime.getRuntime().exec(command);
System.out.println("Running " + exec);
process.waitFor();
强烈建议,如果下一步要做的就是使用jar。下载可能需要几秒钟。尝试使用
File file = new File("FileName.jar");
FileOutputStream fileOut = new FileOutputStream(file);
然后将inChar
追加,并在for循环之后立即写入,如:
for (int i = 0; i < size && inChar != -1; i++) {
// append
}
fos.write(inChar);
for(int i=0;i
请检查您的URLhttp://www.pirategame.net/webstart/privateers.jar
不使用下载browser@Sarz很公平。未经审查的链接。我怀疑我是否关心代码被盗,因为它只在服务器存在的情况下才起作用。此外,在这种情况下,查看文件时,可能仍然会有一些文本告诉浏览器重定向到某个下载URL。因此,如果没有二进制转储,请尝试使用.txt结尾。使用BufferedInputStream/BufferedOutputStream将加快速度。更好:Files.copy(输入,oFile.toPath,StaqndardCopyOption.REPLACE_EXISTING)如果大小
不正确,则可能出现code>。@JoopEggen文件似乎没有问题。还有,一个.txt结尾会做什么?这个复制的东西有什么用/我会在哪里使用它?以这种方式测试“inChar”是徒劳的。破坏已经造成了,就像Op的原始代码一样。必须在读取后立即对其进行测试。
for (int i = 0; i < size && inChar != -1; i++) {
// append
}
fos.write(inChar);