之前在网上随便找了下面Java代码上传文件到FTP服务器,但是自从换了一个FTP服务器下面的代码就不好使了,上传也不报错,就是无法上传。但是会生成一个xxx.tmp文件在FTP上

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
public void upload(String localFile, String remoteFile) throws FtpProtocolException  
{
this.localfilename = localFile;
this.remotefilename = remoteFile;
OutputStream os = null;
FileInputStream is = null;
try
{

os = ftpClient.putFileStream(this.remotefilename, true);

File file_in = new File(this.localfilename);
is = new FileInputStream(file_in);

byte[] bytes = new byte[1024];
int c;
while ((c = is.read(bytes)) != -1)
{
os.write(bytes, 0, c);
}
System.out.println("upload to FTP success");
} catch (IOException ex)
{
System.out.println("not upload to FTP");
ex.printStackTrace();
throw new RuntimeException(ex);
} finally
{
try
{
if (is != null)
{
is.close();
}
} catch (IOException e)
{
e.printStackTrace();
} finally
{
try
{
if (os != null)
{
os.close();
}
} catch (IOException e)
{
e.printStackTrace();
}
}
}
}

折腾了一下改为下面代码就可以上传成功了,不会有tmp文件生成

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
public void upload(String localFile, String remoteFile) throws FtpProtocolException  
{
this.localfilename = localFile;
this.remotefilename = remoteFile;
FileInputStream is = null;
try
{

File file_in = new File(this.localfilename);
is = new FileInputStream(file_in);
ftpClient.putFile(remoteFile, is);
} catch (IOException ex)
{
System.out.println("not upload to FTP");
ex.printStackTrace();
throw new RuntimeException(ex);
} finally
{
try
{
if (is != null)
{
is.close();
}
} catch (IOException e)
{
e.printStackTrace();
}
}
}

具体原因不得而知,反正问题是解决了