java怎麼讀取資料
#1、從控制台讀取資料
使用Scanner類別來讀取控制台的輸入(推薦教學:#java教學)
public static void main(String[] args) { Scanner in = new Scanner(System.in); String a = in.nextLine(); System.out.println(a); }
2、從本機讀取檔案
#使用FileInputStream、InputStreamReader、BufferedReader類別讀取本機資料
public void readTxtFile(String filePath) { try { File file = new File(filePath); if (file.isFile() && file.exists()) { InputStreamReader isr = new InputStreamReader(new FileInputStream(file), "utf-8"); BufferedReader br = new BufferedReader(isr); String lineTxt = null; while ((lineTxt = br.readLine()) != null) { System.out.println(lineTxt); } br.close(); } else { System.out.println("文件不存在!"); } } catch (Exception e) { System.out.println("文件读取错误!"); } }
3、從網路讀取檔案
使用URLConnection 、InputStreamReader、BufferedReader讀取網路資料。
public class Main { public static void main(String[] args) { String url = "//m.sbmmt.com/test.txt"; String result = ""; BufferedReader in = null; try { //生成URL URL realUrl = new URL(url); //初始化连接到特定URL的连接通道 URLConnection connection = realUrl.openConnection(); //开始实际连接 connection.connect(); //数据读取 in = new BufferedReader(new InputStreamReader(connection.getInputStream())); //临时存储一行数据 String line; while((line = in.readLine()) != null) { result += line; } } catch (Exception e) { e.printStackTrace(); } finally { try { if (in != null) { in.close(); } } catch (Exception e2) { e2.printStackTrace(); } } System.out.println(result); } }
以上是java怎麼讀取數據的詳細內容。更多資訊請關注PHP中文網其他相關文章!