我想创建存在于一个 ftp 位置的文件的 zip 文件,并将此 zip 文件复制到其他 ftp 位置而不在本地保存。
我能够处理小文件。它适用于 1 mb 等的小文件
但是如果文件大小很大,比如 100 MB、200 MB、300 MB,那么它会给出错误,
java.io.FileNotFoundException: STOR myfile.zip : 550 The process cannot access the
file because it is being used by another process.
at sun.net.ftp.FtpClient.readReply(FtpClient.java:251)
at sun.net.ftp.FtpClient.issueCommand(FtpClient.java:208)
at sun.net.ftp.FtpClient.openDataConnection(FtpClient.java:398)
at sun.net.ftp.FtpClient.put(FtpClient.java:609)
我的代码是
URLConnection urlConnection=null;
ZipOutputStream zipOutputStream=null;
InputStream inputStream = null;
byte[] buf;
int ByteRead,ByteWritten=0;
***Destination where file will be zipped***
URL url = new URL("ftp://" + ftpuser+ ":" + ftppass + "@"+ ftppass + "/" +
fileNameToStore + ";type=i");
urlConnection=url.openConnection();
OutputStream outputStream = urlConnection.getOutputStream();
zipOutputStream = new ZipOutputStream(outputStream);
buf = new byte[size];
for (int i=0; i<li.size(); i++)
{
try
{
***Souce from where file will be read***
URL u= new URL((String)li.get(i)); // this li has values http://xyz.com/folder
/myPDF.pdf
URLConnection uCon = u.openConnection();
inputStream = uCon.getInputStream();
zipOutputStream.putNextEntry(new ZipEntry((String)li.get(i).substring((int)li.get(i).lastIndexOf("/")+1).trim()));
while ((ByteRead = inputStream .read(buf)) != -1)
{
zipOutputStream.write(buf, 0, ByteRead);
ByteWritten += ByteRead;
}
zipOutputStream.closeEntry();
}
catch(Exception e)
{
e.printStackTrace();
}
}
if (inputStream != null) {
try {
inputStream .close();
}
catch (Exception e) {
e.printStackTrace();
}
}
if (zipOutputStream != null) {
try {
zipOutputStream.close();
} catch (Exception e){
e.printStackTrace();
}
}
谁能告诉我如何避免这个错误并处理大文件
最佳答案
这与文件大小无关;如错误所述,您无法替换该文件,因为其他进程当前正在锁定它。
之所以您更经常看到大文件,是因为这些文件的传输时间更长,因此并发访问的机会更高。
因此,唯一的解决办法是确保在您尝试传输文件时没有人使用该文件。祝你好运。
可能的其他解决方案:
- 不要在服务器上使用 Windows。
- 以临时名称传输文件,完成后重命名。这样,其他进程就不会看到不完整的文件。总是一件好事。
- 使用rsync而不是再次发明轮子。
关于java - 压缩存在于一个 FTP 位置的文件并直接复制到另一个 FTP 位置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12933180/