JAVA中如何通过IP和端口连接到远程计算机并读取文件?

Python09

JAVA中如何通过IP和端口连接到远程计算机并读取文件?,第1张

如此类似也

import java.net.*

import java.io.*

public class FtpConn

{

public static void main(String [] args)throws Exception

{

URL u=new URL("ftp://ppmm:1111@localhost/read1.txt")

URLConnection urlconn=u.openConnection()

BufferedReader br=new BufferedReader(new InputStreamReader(urlconn.getInputStream()))

String line

while(null!=(line=br.readLine()))

{

System.out.println(line)

}

}

}

ftp://ppmm:1111@localhost/read1.txt

其中localhost是ftp server地址

ppmm是用户名

1111是密码

匿名用户不用写用户名和密码如

ftp://localhost/read1.txt

就可以了

import java.io.BufferedReader

import java.io.File

import java.io.FileReader

/**

* @author lmq

*

*/

public class RemoteFile {

public static void main(String[] args) throws Exception {

File remoteFile = new File("//192.168.7.146/test/1.txt")// 192.168.7.146是对方机器IP,test是对方那个共享文件夹名字,如果没有共享是访问不到的

//远程文件其实主要是地址,地址弄对了就和本地文件没什么区别 ,windows里面//或者\\\\开头就表示这个文件是网络路径了其实这个地址就像我们再windows里面,点击开始

//然后点击运行,然后输入 \\192.168.7.146/test/1.txt访问远程文件一样的

BufferedReader br = new BufferedReader(new FileReader(remoteFile))

String str

while ((str = br.readLine()) != null) {

System.out.println(str)

}

br.close()

}

}

1、远程读取数据的原则,是存在url可以指向该文件。

2、很显然,你的局域网上,肯定是不行的。

3、方法:通过ftp或是发布到网上的方式,提供一个可访问到的网络地址就可以了。