java實現(xiàn)讀取txt文件中的內(nèi)容
我們先來看個例子
import java.io.*;
/**
* Created by liguoqing on 2016/3/28.
*/
public class ReadTxtFile {
public static void readTxt(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("文件讀取錯誤!");
}
}
public static void main(String[] args) {
String filePath = "D:\\test\\我.txt";
readTxt(filePath);
}
}
看完上面的例子,我們再來詳細研究下
java讀取txt文件內(nèi)容??梢宰魅缦吕斫猓?/p>
首先獲得一個文件句柄。File file = new File(); file即為文件句柄。兩人之間連通電話網(wǎng)絡(luò)了。接下來可以開始打電話了。
通過這條線路讀取甲方的信息:new FileInputStream(file) 目前這個信息已經(jīng)讀進來內(nèi)存當(dāng)中了。接下來需要解讀成乙方可以理解的東西
既然你使用了FileInputStream()。那么對應(yīng)的需要使用InputStreamReader()這個方法進行解讀剛才裝進來內(nèi)存當(dāng)中的數(shù)據(jù)
解讀完成后要輸出呀。那當(dāng)然要轉(zhuǎn)換成IO可以識別的數(shù)據(jù)呀。那就需要調(diào)用字節(jié)碼讀取的方法BufferedReader()。同時使用bufferedReader()的readline()方法讀取txt文件中的每一行數(shù)據(jù)哈。
package com.campu;
import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.io.Reader;
/**
* @author 碼農(nóng)小江
* H20121012.java
* 2012-10-12下午11:40:21
*/
public class H20121012 {
/**
* 功能:Java讀取txt文件的內(nèi)容
* 步驟:1:先獲得文件句柄
* 2:獲得文件句柄當(dāng)做是輸入一個字節(jié)碼流,需要對這個輸入流進行讀取
* 3:讀取到輸入流后,需要讀取生成字節(jié)流
* 4:一行一行的輸出。readline()。
* 備注:需要考慮的是異常情況
* @param filePath
*/
public static void readTxtFile(String filePath){
try {
String encoding="GBK";
File file=new File(filePath);
if(file.isFile() && file.exists()){ //判斷文件是否存在
InputStreamReader read = new InputStreamReader(
new FileInputStream(file),encoding);//考慮到編碼格式
BufferedReader bufferedReader = new BufferedReader(read);
String lineTxt = null;
while((lineTxt = bufferedReader.readLine()) != null){
System.out.println(lineTxt);
}
read.close();
}else{
System.out.println("找不到指定的文件");
}
} catch (Exception e) {
System.out.println("讀取文件內(nèi)容出錯");
e.printStackTrace();
}
}
public static void main(String argv[]){
String filePath = "L:\\Apache\\htdocs\\res\\20121012.txt";
// "res/";
readTxtFile(filePath);
}
}
相關(guān)文章
生產(chǎn)環(huán)境NoHttpResponseException異常排查解決記錄分析
這篇文章主要為大家介紹了生產(chǎn)環(huán)境NoHttpResponseException異常排查解決記錄分析,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪2023-10-10
Java如何使用ConfigurationProperties獲取yml中的配置
這篇文章主要介紹了Java如何使用ConfigurationProperties獲取yml中的配置,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2022-02-02
教你用Springboot實現(xiàn)攔截器獲取header內(nèi)容
項目中遇到一個需求,對接上游系統(tǒng)是涉及到需要增加請求頭,請求頭的信息是動態(tài)獲取的,需要動態(tài)從下游拿到之后轉(zhuǎn)給上游,文中非常詳細的介紹了該需求的實現(xiàn),需要的朋友可以參考下2021-05-05

