如果file的文件路径是远程计算机【new File(http://123.456.789.999/java/test.txt)】,网速不给力,那它的exists()方法来判断文件是否存在【new File(http://123.456.789.999/java/test.txt).exists()】,它会等待连接吗,连接上再判断不, 求个方法来连接指定的服务器例如:123.456.678.999(服务器正常) 该方法来判断服务器上文件的存在?
//判断文件是否存在
public static String fileExists(String plainFilePath){
File file=new File(plainFilePath);
if(!file.exists()) {
return "false";
} else{
return "true";
}
}
用URL类以及httpurlconnection可以判断追问
给点思路指教一下
追答import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;
import ch.unifr.article.util.Constant;
public class ReadInformation {
/**
* @param args
*/
private InputStream l_urlStream;
private FileWriter fw;
private String coding = "UTF-8";
public String getUrlText(String s) {
String text = "";
String sCurrentLine = "";
try {
URL url = new URL(s);
java.net.HttpURLConnection l_connection = (java.net.HttpURLConnection) url
.openConnection();
l_connection.connect();
l_urlStream = l_connection.getInputStream();
java.io.InputStreamReader read = new InputStreamReader(l_urlStream,
coding);
java.io.BufferedReader l_reader = new java.io.BufferedReader(read);
while ((sCurrentLine = l_reader.readLine()) != null) {
text += sCurrentLine;
}// viewSource(url);
} catch (MalformedURLException ex) {
System.out.println("网络连接错误:" + s);
ex.printStackTrace();
} catch (FileNotFoundException e) {
System.out.println("文件不存在:" + s);
e.printStackTrace();
} catch (IOException e) {
System.out.println("其他IO错误:" + s);
e.printStackTrace();
}
return text;
}
public static void main(String[] args) {
ReadInformation ri = new ReadInformation();
String url = "";//此处请lz填写txt地址
System.out.println(ri.getUrlText(url));
}
}
你可以用net包下面的url跟httpurlconnection这两个类看看本回答被提问者采纳