依赖:
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
|
<dependencies>
<!-- https://mvnrepository.com/artifact/org.apache.commons/commons-vfs2 -->
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-vfs2</artifactId>
<version>2.2</version>
</dependency>
<!--当需要使用commons-vfs的sftp功能用-->
<dependency>
<groupId>com.jcraft</groupId>
<artifactId>jsch</artifactId>
<version>0.1.53</version>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-io</artifactId>
<version>1.3.2</version>
</dependency>
<!-- https://mvnrepository.com/artifact/joda-time/joda-time -->
<dependency>
<groupId>joda-time</groupId>
<artifactId>joda-time</artifactId>
<version>2.9.9</version>
</dependency>
</dependencies>
|
测试类:
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
53
54
55
56
57
58
59
60
61
62
63
|
import
org.apache.commons.io.IOUtils;
import
org.apache.commons.vfs2.FileObject;
import
org.apache.commons.vfs2.FileSystemManager;
import
org.apache.commons.vfs2.FileSystemOptions;
import
org.apache.commons.vfs2.VFS;
import
org.apache.commons.vfs2.provider.sftp.SftpFileSystemConfigBuilder;
import
org.joda.time.DateTime;
import
org.joda.time.format.DateTimeFormat;
import
java.io.File;
/**
* @author by lei zhou on 2017/11/13 11:15.
*/
public
class
Tester {
public
static
void
main(String[] args) {
resolveFile(
"res:1/11111"
);
resolveFile(
"zip://"
+ System.getProperty(
"user.dir"
) + File.separator +
"c.zip"
);
resolveFile(
"file://"
+ System.getProperty(
"user.dir"
) + File.separator +
"Java9Test.iml"
);
resolveFile(
"sftp://test:test@192.168.1.111:22/home/zhoulei"
);
}
public
static
void
resolveFile(String path) {
try
{
FileSystemManager fsManager = VFS.getManager();
FileSystemOptions opts =
new
FileSystemOptions();
if
(path.startsWith(
"sftp:"
)) {
// 设false时,URI要传绝对路径,设true时,URI传相对于远程用户根目录的相对路径
SftpFileSystemConfigBuilder.getInstance().setUserDirIsRoot(opts,
false
);
SftpFileSystemConfigBuilder.getInstance().setStrictHostKeyChecking(opts,
"no"
);
SftpFileSystemConfigBuilder.getInstance().setTimeout(opts,
10000
);
}
FileObject fileObject = fsManager.resolveFile(path, opts);
if
(fileObject.isFolder()) {
FileObject[] childs = fileObject.getChildren();
for
(FileObject child : childs) {
print(child);
}
}
else
{
print(fileObject);
}
}
catch
(Exception e) {
e.printStackTrace();
}
}
private
static
void
print(FileObject fileObject)
throws
Exception {
System.out.println(fileObject.getPublicURIString() +
" "
+ getFormatedDateTime(fileObject.getContent().getLastModifiedTime()) +
" "
+ IOUtils.toString(fileObject.getContent().getInputStream(),
"UTF-8"
));
}
private
static
String getFormatedDateTime(
long
millis) {
return
(
new
DateTime(millis)).toString(DateTimeFormat.fullDateTime());
}
}
|
项目结构:
本文转自 zl1030 51CTO博客,原文链接:http://blog.51cto.com/zl1030/1981324