① java 怎么使用远程 url 创建 file
importjava.io.BufferedReader;
importjava.io.File;
importjava.io.FileReader;
/**
*@authorlmq
*
*/
publicclassRemoteFile{
publicstaticvoidmain(String[]args)throwsException{
FileremoteFile=newFile("//192.168.7.146/test/1.txt");//192.168.7.146是对方机器IP,test是对方那个共享文件夹名字,如果没有共享是访问不到的
//远程文件其实主要是地址,地址弄对了就和本地文件没什么区别,windows里面//或者\\开头就表示这个文件是网络路径了其实这个地址就像我们再windows里面,点击开始
//然后点击运行,然后输入\192.168.7.146/test/1.txt访问远程文件一样的
BufferedReaderbr=newBufferedReader(newFileReader(remoteFile));
Stringstr;
while((str=br.readLine())!=null){
System.out.println(str);
}
br.close();
}
}
如果是非共享文件 你只能通过url读取流来生成了
publicvoiddownUrlTxt(StringfileName,StringfileUrl,StringdownPath){
FilesavePath=newFile(downPath);
if(!savePath.exists()){
savePath.mkdir();
}
String[]urlname=fileUrl.split("/");
intlen=urlname.length-1;
Stringuname=urlname[len];//获取文件名
try{
Filefile=newFile(savePath+"/"+uname);//创建新文件
if(file!=null&&!file.exists()){
file.createNewFile();
}
OutputStreamoputstream=newFileOutputStream(file);
URLurl=newURL(fileUrl);
HttpURLConnectionuc=(HttpURLConnection)url.openConnection();
uc.setDoInput(true);//设置是否要从URL连接读取数据,默认为true
uc.connect();
InputStreamiputstream=uc.getInputStream();
System.out.println("filesizeis:"+uc.getContentLength());//打印文件长度
byte[]buffer=newbyte[4*1024];
intbyteRead=-1;
while((byteRead=(iputstream.read(buffer)))!=-1){
oputstream.write(buffer,0,byteRead);
}
oputstream.flush();
iputstream.close();
oputstream.close();
}catch(Exceptione){
System.out.println("读取失败!");
e.printStackTrace();
}
System.out.println("生成文件路径:"+downPath+fileName);
}