简体   繁体   中英

read remote file in Java

OS: macbook

I wanna read remote file in Java. I test it on my local computer first.

  1. I tried to use File , but you guys told me File can only be used on local file system, thanks.

     public static void main(String[] args) throws URISyntaxException { URI uri = new URI("file://127.0.0.1/Users/jian/Public/logfiles/Hadoop/hdp_log1.log"); File file = new File(uri); System.out.println(file.exists()); } 
  2. I find a library for Macbook, Samba JCIFS , from this link access to file using Java with Samba JCIFS . Here is my code :

     public static void main(String[] args) throws URISyntaxException, MalformedURLException, SmbException { NtlmPasswordAuthentication auth = new NtlmPasswordAuthentication("","jian", "ywnk"); SmbFile smbFile = new SmbFile("smb://127.0.0.1/Users/jian/Public/logfiles/Hadoop/hdp_log1.log",auth); System.out.println(smbFile.exists()); } 

Then I got this error:
Exception in thread "main" jcifs.smb.SmbAuthException: Logon failure: unknown user name or bad password.
username is the same as I run who am i in terminal, and password is my login password. I don't know why I get this username or password incorrect error.
Thanks for your guys help.

File cannot be used to read "remote files". It is meant to be used for filesystem objects which are only local to the machine, or to be more precise, accessible from the local filesystem.

It so happens that with Unix systems you can have mount points to remote filesystems, for instance an NFS mount, or a FUSE mount. But those will always be seen as "local".

If what you want is to access a remote resource to be viewed as a "file", then File can't do it.

But JSR 203 can. See here for an example.

Therefore, you first need to define what you mean by a "remote file". It entirely depends on the protocol you use. And File cannot do it. Unless the OS has sorted it for you (that is, as mentioned above, you have an NFS mount, a FUSE mount or other).


As to your error, the File constructor warns you that there is an authority component in your URI; and there is: 127.0.0.1 . As File expects nothing but a path component to the URI (in addition to the URI scheme, file ), this explains the error.

Your requirement can easily be fulfilled by some java FTP library.

Take a look at ftp4j , its a good library for upload and download of files and also, for directory listings.

Apache commons-net is also a good option. They have some really good sample programs too.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM