java file url_java 怎么使用远程 url 创建 file

展开全部

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是对方那个共享文件夹名字,如果没有共享是访问不到的

//远程文件其实主要是地32313133353236313431303231363533e59b9ee7ad9431333335306265址,地址弄对了就和本地文件没什么区别 ,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();

}

}

如果是非共享文件 你只能通过url读取流来生成了public void downUrlTxt(String fileName,String fileUrl,String downPath){

File savePath = new File(downPath);

if (!savePath.exists()) {

savePath.mkdir();

}

String[] urlname = fileUrl.split("/");

int len = urlname.length-1;

String uname = urlname[len];//获取文件名

try {

File file = new File(savePath+"/"+uname);//创建新文件

if(file!=null && !file.exists()){

file.createNewFile();

}

OutputStream oputstream = new FileOutputStream(file);

URL url = new URL(fileUrl);

HttpURLConnection uc = (HttpURLConnection) url.openConnection();

uc.setDoInput(true);//设置是否要从 URL 连接读取数据,默认为true

uc.connect();

InputStream iputstream = uc.getInputStream();

System.out.println("file size is:"+uc.getContentLength());//打印文件长度

byte[] buffer = new byte[4*1024];

int byteRead = -1;

while((byteRead=(iputstream.read(buffer)))!= -1){

oputstream.write(buffer, 0, byteRead);

}

oputstream.flush();

iputstream.close();

oputstream.close();

} catch (Exception e) {

System.out.println("读取失败!");

e.printStackTrace();

}

System.out.println("生成文件路径:"+downPath+fileName);

}

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值