java文本讀取
『壹』 java如何讀取一個txt文件的所有內容
importjava.io.BufferedInputStream;
importjava.io.BufferedReader;
importjava.io.File;
importjava.io.FileInputStream;
importjava.io.InputStreamReader;
importjava.io.Reader;
publicclassH{
/**
*功能:Java讀取txt文件的內容
*步驟:1:先獲得文件句柄
*2:獲得文件句柄當做是輸入一個位元組碼流,需要對這個輸入流進行讀取
*3:讀取到輸入流後,需要讀取生成位元組流
*4:一行一行的輸出。readline()。
*備註:需要考慮的是異常情況
*@paramfilePath
*/
publicstaticvoidreadTxtFile(StringfilePath){
try{
Stringencoding="GBK";
Filefile=newFile(filePath);
if(file.isFile()&&file.exists()){//判斷文件是否存在
InputStreamReaderread=newInputStreamReader(
newFileInputStream(file),encoding);//考慮到編碼格式
BufferedReaderbufferedReader=newBufferedReader(read);
StringlineTxt=null;
while((lineTxt=bufferedReader.readLine())!=null){
System.out.println(lineTxt);
}
read.close();
}else{
System.out.println("找不到指定的文件");
}
}catch(Exceptione){
System.out.println("讀取文件內容出錯");
e.printStackTrace();
}
}
publicstaticvoidmain(Stringargv[]){
StringfilePath="L:\20121012.txt";
//"res/";
readTxtFile(filePath);
}}
『貳』 JAVA中讀取文件(二進制,字元)內容的幾種方
JAVA中讀取文件內容的方法有很多,比如按位元組讀取文件內容,按字元讀取文件內容,按行讀取文件內容,隨機讀取文件內容等方法,本文就以上方法的具體實現給出代碼,需要的可以直接復制使用
public class ReadFromFile {
/**
* 以位元組為單位讀取文件,常用於讀二進制文件,如圖片、聲音、影像等文件。
*/
public static void readFileByBytes(String fileName) {
File file = new File(fileName);
InputStream in = null;
try {
System.out.println("以位元組為單位讀取文件內容,一次讀一個位元組:");
// 一次讀一個位元組
in = new FileInputStream(file);
int tempbyte;
while ((tempbyte = in.read()) != -1) {
System.out.write(tempbyte);
}
in.close();
} catch (IOException e) {
e.printStackTrace();
return;
}
try {
System.out.println("以位元組為單位讀取文件內容,一次讀多個位元組:");
// 一次讀多個位元組
byte[] tempbytes = new byte[100];
int byteread = 0;
in = new FileInputStream(fileName);
ReadFromFile.showAvailableBytes(in);
// 讀入多個位元組到位元組數組中,byteread為一次讀入的位元組數
while ((byteread = in.read(tempbytes)) != -1) {
System.out.write(tempbytes, 0, byteread);
}
} catch (Exception e1) {
e1.printStackTrace();
} finally {
if (in != null) {
try {
in.close();
} catch (IOException e1) {
}
}
}
}
/**
* 以字元為單位讀取文件,常用於讀文本,數字等類型的文件
*/
public static void readFileByChars(String fileName) {
File file = new File(fileName);
Reader reader = null;
try {
System.out.println("以字元為單位讀取文件內容,一次讀一個位元組:");
// 一次讀一個字元
reader = new InputStreamReader(new FileInputStream(file));
int tempchar;
while ((tempchar = reader.read()) != -1) {
// 對於windows下,\r\n這兩個字元在一起時,表示一個換行。
// 但如果這兩個字元分開顯示時,會換兩次行。
// 因此,屏蔽掉\r,或者屏蔽\n。否則,將會多出很多空行。
if (((char) tempchar) != '\r') {
System.out.print((char) tempchar);
}
}
reader.close();
} catch (Exception e) {
e.printStackTrace();
}
try {
System.out.println("以字元為單位讀取文件內容,一次讀多個位元組:");
// 一次讀多個字元
char[] tempchars = new char[30];
int charread = 0;
reader = new InputStreamReader(new FileInputStream(fileName));
// 讀入多個字元到字元數組中,charread為一次讀取字元數
while ((charread = reader.read(tempchars)) != -1) {
// 同樣屏蔽掉\r不顯示
if ((charread == tempchars.length)
&& (tempchars[tempchars.length - 1] != '\r')) {
System.out.print(tempchars);
} else {
for (int i = 0; i < charread; i++) {
if (tempchars[i] == '\r') {
continue;
} else {
System.out.print(tempchars[i]);
}
}
}
}
} catch (Exception e1) {
e1.printStackTrace();
} finally {
if (reader != null) {
try {
reader.close();
} catch (IOException e1) {
}
}
}
}
/**
* 以行為單位讀取文件,常用於讀面向行的格式化文件
*/
public static void readFileByLines(String fileName) {
File file = new File(fileName);
BufferedReader reader = null;
try {
System.out.println("以行為單位讀取文件內容,一次讀一整行:");
reader = new BufferedReader(new FileReader(file));
String tempString = null;
int line = 1;
// 一次讀入一行,直到讀入null為文件結束
while ((tempString = reader.readLine()) != null) {
// 顯示行號
System.out.println("line " + line + ": " + tempString);
line++;
}
reader.close();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (reader != null) {
try {
reader.close();
} catch (IOException e1) {
}
}
}
}
/**
* 隨機讀取文件內容
*/
public static void readFileByRandomAccess(String fileName) {
RandomAccessFile randomFile = null;
try {
System.out.println("隨機讀取一段文件內容:");
// 打開一個隨機訪問文件流,按只讀方式
randomFile = new RandomAccessFile(fileName, "r");
// 文件長度,位元組數
long fileLength = randomFile.length();
// 讀文件的起始位置
int beginIndex = (fileLength > 4) ? 4 : 0;
// 將讀文件的開始位置移到beginIndex位置。
randomFile.seek(beginIndex);
byte[] bytes = new byte[10];
int byteread = 0;
// 一次讀10個位元組,如果文件內容不足10個位元組,則讀剩下的位元組。
// 將一次讀取的位元組數賦給byteread
while ((byteread = randomFile.read(bytes)) != -1) {
System.out.write(bytes, 0, byteread);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
if (randomFile != null) {
try {
randomFile.close();
} catch (IOException e1) {
}
}
}
}
/**
* 顯示輸入流中還剩的位元組數
*/
private static void showAvailableBytes(InputStream in) {
try {
System.out.println("當前位元組輸入流中的位元組數為:" + in.available());
} catch (IOException e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
String fileName = "C:/temp/newTemp.txt";
ReadFromFile.readFileByBytes(fileName);
ReadFromFile.readFileByChars(fileName);
ReadFromFile.readFileByLines(fileName);
ReadFromFile.readFileByRandomAccess(fileName);
}
}
『叄』 如何用java讀取txt文件的內容
import java.io.*; public class Read{ public static void main(String [] args) { try{
FileReader f = new FileReader("D:\\1.txt"); // 注意路徑這里可以有兩種表示方法一個種\\一種/就可以了 BufferedReader buf = new BufferedReader(f);
String s; while((s = buf.readLine() ) != null){ System.out.println(s); } f.close(); buf.close();
}catch(IOException e){} }}
『肆』 java文件如何讀取
有幾種方法讀取吧
File
file
=
new
File("d:\\a.txt");//把D盤目錄下的a.txt讀取出來,
InputStream
is
=
new
FileInputStream(file);//把文件以位元組流讀到內存中
第二種是類載入
Demo1.class.getClassLoader().getResourceAsStream("a.txt");//Demo1為當前類名,a.txt在與Demo1.class在同一目錄下。
還有其它的就不說了
『伍』 java讀取txt的數據並處理
直接給你一段實際可以用的代碼吧
/**
*讀取一行一行的文件
*
*@paramfilename
*@return
*@throwsIOException
*/
publicstaticList<String>readLinedFile(Stringfilename){
List<String>filecon=newArrayList<String>();
Stringm="";
BufferedReaderfile=null;
try{
file=newBufferedReader(newFileReader(filename));
while((m=file.readLine())!=null){
if(!m.equals(""))//不需要讀取空行
{
filecon.add(m);
}
}
file.close();
}catch(IOExceptione){
e.printStackTrace();
}
returnfilecon;
}
這段代碼實現了,你傳入文件的路徑,給你讀出一個String的List,一個String就是文件的一行,拿到這個List,你愛怎麼處理就怎麼處理,就比如你現在這個需求吧,就把這個List拿來遍歷
//這個是去除不含genotype字元串後的數組
List<String>resultList=newArrayList<String>();
for(Stringline:filecon){
if(line.indexOf("genotype")!=-1){
resultList.add(line);
}
}
這樣處理完後就拿到了一個只有含有 genotype的數組,然後剩下的就是把這個數組寫到一個文件裡面,我給你看一個把字元串數組寫到文件的方法,你可以拿去直接用
/**
*寫入一行一行的文件
*@paramlst要寫入的字元串數組
*@paramfilename要寫入的文件路徑
*@return
*@throwsIOException
*/
(Listlst,StringfilePath)throwsIOException{
Filefile=newFile(filePath);
BufferedWriterout=newBufferedWriter(newFileWriter(file,false));
for(inti=0;i<lst.size();i++){
Stringtemp=(String)lst.get(i);
if(!StringUtils.isBlank(temp)){
out.write(temp);
out.newLine();
}
}
out.close();
out=null;
file=null;
}
這樣懂了吧?
『陸』 Java 如何讀取txt文件的內容
java讀取txt文件內容。可以作如下理解:
首先獲得一個文件句柄。File file = new File(); file即為文件句柄。兩人之間連通電話網路了。接下來可以開始打電話了。
通過這條線路讀取甲方的信息:new FileInputStream(file) 目前這個信息已經讀進來內存當中了。接下來需要解讀成乙方可以理解的東西
既然你使用了FileInputStream()。那麼對應的需要使用InputStreamReader()這個方法進行解讀剛才裝進來內存當中的數據
解讀完成後要輸出呀。那當然要轉換成IO可以識別的數據呀。那就需要調用位元組碼讀取的方法BufferedReader()。同時使用bufferedReader()的readline()方法讀取txt文件中的每一行數據哈。
packagecom.campu;
importjava.io.BufferedInputStream;
importjava.io.BufferedReader;
importjava.io.File;
importjava.io.FileInputStream;
importjava.io.InputStreamReader;
importjava.io.Reader;
/**
*@authorJava團長
*H20121012.java
*2017-10-29上午11:22:21
*/
publicclassH20121012{
/**
*功能:Java讀取txt文件的內容
*步驟:1:先獲得文件句柄
*2:獲得文件句柄當做是輸入一個位元組碼流,需要對這個輸入流進行讀取
*3:讀取到輸入流後,需要讀取生成位元組流
*4:一行一行的輸出。readline()。
*備註:需要考慮的是異常情況
*@paramfilePath
*/
publicstaticvoidreadTxtFile(StringfilePath){
try{
Stringencoding="GBK";
Filefile=newFile(filePath);
if(file.isFile()&&file.exists()){//判斷文件是否存在
InputStreamReaderread=newInputStreamReader(
newFileInputStream(file),encoding);//考慮到編碼格式
BufferedReaderbufferedReader=newBufferedReader(read);
StringlineTxt=null;
while((lineTxt=bufferedReader.readLine())!=null){
System.out.println(lineTxt);
}
read.close();
}else{
System.out.println("找不到指定的文件");
}
}catch(Exceptione){
System.out.println("讀取文件內容出錯");
e.printStackTrace();
}
}
publicstaticvoidmain(Stringargv[]){
StringfilePath="L:\Apache\htdocs\res\20121012.txt";
//"res/";
readTxtFile(filePath);
}}
我有一個微信公眾號,經常會分享一些Java技術相關的干貨文章,還有一些學習資源。
如果你需要的話,可以用微信搜索「Java團長」或者「javatuanzhang」關注。
『柒』 java怎麼讀取文本文件中的所有字元
可以用文件流FileInputStream的方式讀取,如果文本文件太大了,不建議一次性往內存中讀,那往往會使之溢出。也可以一行行的讀取,用BufferReader讀,具體的實例都可以網路得到的。
『捌』 java讀取文本文檔
//僅提供一些關鍵語句,不可直接運行,具體自己去實現
//自己多查查Java API
import java.io.*;//導入操作要用到的類
File file=new File("c:/test.txt");//源文件位置
FileReader fr=new FileReader(file);//創建文件輸入流
BufferedReader in=new BufferedReader(fr);//包裝文件輸入流,可整行讀取
String line;
while((line=in.readLine()) != null) {
//循環里逐行讀取到字元串line
String[] str=line.split(" ")//以空格為間隔將這一行拆分成一組小字元串
int []num=new int[100];
num[i]=Integer.parseInt(str[i]);//將拆分的字元串解析為整數
int sum=num[0]+num[1]
//進行運算操作
}
『玖』 java如何讀取txt文件內容
給你兩個方法,你可以看看;
//獲取值返回String文本
publicStringtxt2String(StringfilePath){
Filefile=newFile(filePath);
StringBuilderresult=newStringBuilder();
try{
BufferedReaderbr=newBufferedReader(newFileReader(file));//構造一個BufferedReader類來讀取文件
Strings=null;
while((s=br.readLine())!=null){//使用readLine方法,一次讀一行
result.append(s+System.lineSeparator());
}
br.close();
}catch(Exceptione){
e.printStackTrace();
}
returnresult.toString();
}
//獲取值不返回String文本
publicvoidreadTxtFile(StringfilePath){
try{
Stringencoding="GBK";
Filefile=newFile(filePath);
if(file.isFile()&&file.exists()){//判斷文件是否存在
InputStreamReaderread=newInputStreamReader(
newFileInputStream(file),encoding);//考慮到編碼格式
BufferedReaderbufferedReader=newBufferedReader(read);
StringlineTxt=null;
while((lineTxt=bufferedReader.readLine())!=null){
System.out.println(lineTxt);
}
read.close();
}else{
System.out.println("找不到指定的文件");
}
}catch(Exceptione){
System.out.println("讀取文件內容出錯");
e.printStackTrace();
}
}