① 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);
}