读取本地文件
通过本地文件的路径,把文件构造成File,通过流的读取,把文件内容一行行地读到String中。
下面是代码:
public static List getFile(String filePath){
System.out.println("Starting to get file...");
List contents = new ArrayList();
File file = new File(filePath);
try {
InputStream is = new FileInputStream(file);
BufferedReader br = new BufferedReader(new InputStreamReader(is));
String line;
while((line = br.readLine()) != null){
System.out.println(line);
contents.add(line);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
System.out.println("Finished geting file...");
return contents;
}
读取指定网页
通过网页的链接地址,构造URL,获取到Connection之后进行连接,如果连接成功,可以获取到流,最后把流读出到String即可。
下面是代码:
public static StringreadFile(String txtUrl){
System.out.println("Start to get file from URL...");
StringBuilder sb =new StringBuilder();
URL url;
try {
url =new URL(txtUrl);
URLConnection conn = url.openConnection();
conn.connect();
HttpURLConnection httpConn = (HttpURLConnection)conn;
if(httpConn.getResponseCode() == HttpURLConnection.HTTP_OK){
InputStreamReader isr =new InputStreamReader(httpConn.getInputStream());
BufferedReader br =new BufferedReader(isr);
String s;
while((s = br.readLine()) !=null){
sb.append(s);
sb.append(",");
}
sb.deleteCharAt(sb.length()-1);
}else{
System.out.println("Cannot connect to the "+txtUrl);
}
}catch (MalformedURLException e) {
e.printStackTrace();
}catch (IOException e) {
e.printStackTrace();
}
System.out.println("Finished getting the contents from URL...");
return sb.toString();
}
详细可见:java读取本地和网页的文件
网友评论