重慶分公司,新征程啟航
為企業(yè)提供網(wǎng)站建設(shè)、域名注冊(cè)、服務(wù)器等服務(wù)
為企業(yè)提供網(wǎng)站建設(shè)、域名注冊(cè)、服務(wù)器等服務(wù)
這篇文章運(yùn)用簡(jiǎn)單易懂的例子給大家介紹java實(shí)現(xiàn)讀取數(shù)據(jù)的方法,代碼非常詳細(xì),感興趣的小伙伴們可以參考借鑒,希望對(duì)大家能有所幫助。
成都創(chuàng)新互聯(lián)公司是一家專業(yè)提供祿豐企業(yè)網(wǎng)站建設(shè),專注與成都網(wǎng)站設(shè)計(jì)、網(wǎng)站建設(shè)、外貿(mào)網(wǎng)站建設(shè)、html5、小程序制作等業(yè)務(wù)。10年已為祿豐眾多企業(yè)、政府機(jī)構(gòu)等服務(wù)。創(chuàng)新互聯(lián)專業(yè)網(wǎng)絡(luò)公司優(yōu)惠進(jìn)行中。
1、從控制臺(tái)讀取數(shù)據(jù)
使用Scanner類來讀取控制臺(tái)的輸入()
public static void main(String[] args) { Scanner in = new Scanner(System.in); String a = in.nextLine(); System.out.println(a); }
2、從本地讀取文件
使用FileInputStream、InputStreamReader、BufferedReader類讀取本地?cái)?shù)據(jù)
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("文件讀取錯(cuò)誤!"); } }
3、從網(wǎng)絡(luò)讀取文件
使用URLConnection 、InputStreamReader、BufferedReader讀取網(wǎng)絡(luò)數(shù)據(jù)。
public class Main { public static void main(String[] args) { String url = "http://www.php.cn/test.txt"; String result = ""; BufferedReader in = null; try { //生成URL URL realUrl = new URL(url); //初始化連接到特定URL的連接通道 URLConnection connection = realUrl.openConnection(); //開始實(shí)際連接 connection.connect(); //數(shù)據(jù)讀取 in = new BufferedReader(new InputStreamReader(connection.getInputStream())); //臨時(shí)存儲(chǔ)一行數(shù)據(jù) 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); } }
關(guān)于java實(shí)現(xiàn)讀取數(shù)據(jù)的方法就分享到這里了,希望以上內(nèi)容可以對(duì)大家有一定的幫助,可以學(xué)到更多知識(shí)。如果覺得文章不錯(cuò),可以把它分享出去讓更多的人看到。