導航:首頁 > 編程語言 > java字元流讀取

java字元流讀取

發布時間:2022-10-20 21:44:24

java中怎樣將文件的內容讀取成字元串

java中有四種將文件的內容讀取成字元串

方式一:

Java code

/**

*以位元組為單位讀取文件,常用於讀二進制文件,如圖片、聲音、影像等文件。

*當然也是可以讀字元串的。

*/

/*貌似是說網路環境中比較復雜,每次傳過來的字元是定長的,用這種方式?*/

publicStringreadString1()

{

try

{

//FileInputStream用於讀取諸如圖像數據之類的原始位元組流。要讀取字元流,請考慮使用FileReader。

FileInputStreaminStream=this.openFileInput(FILE_NAME);

ByteArrayOutputStreambos=newByteArrayOutputStream();

byte[]buffer=newbyte[1024];

intlength=-1;

while((length=inStream.read(buffer)!=-1)

{

bos.write(buffer,0,length);

//.write方法SDK的解釋是m.

//當流關閉以後內容依然存在

}

bos.close();

inStream.close();

returnbos.toString();

//為什麼不一次性把buffer得大小取出來呢?為什麼還要寫入到bos中呢?returnnew(buffer,"UTF-8")不更好么?

//returnnewString(bos.toByteArray(),"UTF-8");

}

}

方式二:

Java code

方式四:

Java code

/*InputStreamReader+BufferedReader讀取字元串,InputStreamReader類是從位元組流到字元流的橋梁*/

/*按行讀對於要處理的格式化數據是一種讀取的好方式*/

()

{

intlen=0;

StringBufferstr=newStringBuffer("");

Filefile=newFile(FILE_IN);

try{

FileInputStreamis=newFileInputStream(file);

InputStreamReaderisr=newInputStreamReader(is);

BufferedReaderin=newBufferedReader(isr);

Stringline=null;

while((line=in.readLine())!=null)

{

if(len!=0)//處理換行符的問題

{

str.append(" "+line);

}

else

{

str.append(line);

}

len++;

}

in.close();

is.close();

}catch(IOExceptione){

//TODOAuto-generatedcatchblock

e.printStackTrace();

}

returnstr.toString();

}

② java分別以位元組流和字元流的兩種方式讀取文件內容


importjava.io.BufferedReader;

importjava.io.File;

importjava.io.FileInputStream;

importjava.io.IOException;

importjava.io.InputStreamReader;

importjava.io.PrintWriter;

publicclassTest10{

/**

*復制當前的源程序到項目的根目錄

*@throwsIOException

*/

publicstaticvoidmain(String[]args)throwsIOException{

/*

*1:讀取原文件

*2:項目標文件中寫

*3:使用緩沖流按行讀寫

*/

FileInputStreamfis=newFileInputStream("src"+File.separator+"day01"+File.separator+"Test1.java");


//轉化為字元輸出流

InputStreamReaderisr=newInputStreamReader(fis);


//按行為單位讀取字元串

BufferedReaderbr=newBufferedReader(isr);


//

PrintWriterpw=newPrintWriter("Test1.java");


Stringline=null;

while((line=br.readLine())!=null){

pw.println(line);

}

pw.close();

br.close();

}

}

③ 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);
}
}

復制代碼

5、將內容追加到文件尾部

public class AppendToFile {
/**
* A方法追加文件:使用RandomAccessFile
*/
public static void appendMethodA(String fileName, String content) {
try {
// 打開一個隨機訪問文件流,按讀寫方式
RandomAccessFile randomFile = new RandomAccessFile(fileName, "rw");
// 文件長度,位元組數
long fileLength = randomFile.length();
//將寫文件指針移到文件尾。
randomFile.seek(fileLength);
randomFile.writeBytes(content);
randomFile.close();
} catch (IOException e) {
e.printStackTrace();
}
}

/**
* B方法追加文件:使用FileWriter
*/
public static void appendMethodB(String fileName, String content) {
try {
//打開一個寫文件器,構造函數中的第二個參數true表示以追加形式寫文件
FileWriter writer = new FileWriter(fileName, true);
writer.write(content);
writer.close();
} catch (IOException e) {
e.printStackTrace();
}
}

public static void main(String[] args) {
String fileName = "C:/temp/newTemp.txt";
String content = "new append!";
//按方法A追加文件
AppendToFile.appendMethodA(fileName, content);
AppendToFile.appendMethodA(fileName, "append end. \n");
//顯示文件內容
ReadFromFile.readFileByLines(fileName);
//按方法B追加文件
AppendToFile.appendMethodB(fileName, content);
AppendToFile.appendMethodB(fileName, "append end. \n");
//顯示文件內容
ReadFromFile.readFileByLines(fileName);
}
}

④ Java字元流和位元組流對文件操作的區別

Java字元流是處理字元(Char)對象用的,位元組流是處理位元組(Byte)對象用的。處理的目標對象不同,處理方法也就不一樣了。
字元流處理的基本單位是字元(Java中的字元是16位的),輸入流以Reader為基礎,輸出流以Writer為基礎;
位元組流的基本單位是位元組(Java中的位元組是8位的),輸入流以
InputStream為基礎,輸出流以
OutputStream為基礎;
字元流在輸入時可以按字元讀取,也可以按行讀取,會去掉回車換行,常用於讀取字元數據;
而位元組流按位元組讀取,不作任何處理,常用於讀取二進制數據。
Java中的字元在內部都是使用Unicode進行表示的,因此,要正確讀取字元數據,需要知道字元的編碼字元集,字元流提供編碼字元集的指定,如果不指定使用系統默認的方式對字元數據進行編碼轉換,這個編碼字元集不正確,會造成讀進來的地字元出現亂碼。
位元組流雖然是讀取二進制數據用的,但也可以讀取字元文件,按位元組進行處理,讀進來之後可以根據編碼字元集進行轉換,也可以變成字元串。

⑤ java 中 字元流是否可以讀取位元組流寫的 txt文件

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]);
}
}
}
}

⑥ java中位元組流讀寫和字元流讀寫哪個效率更高

Java流在處理上分為字元流和位元組流。字元流處理的單元為2個位元組的Unicode字元,分別操作字元、字元數組或字元串,而位元組流處理單元為1個位元組,操作位元組和位元組數組。Java內用Unicode編碼存儲字元,字元流處理類負責將外部的其他編碼的

⑦ java用字元流讀寫文件

代碼已寫好,希望對你有幫助,順便求好評。

packagearchitecture;

importjava.io.File;
importjava.io.FileNotFoundException;
importjava.io.FileReader;
importjava.io.FileWriter;
importjava.io.IOException;

/**
*
*@authorWangZhenhui
*@blogwww.soaringroad.com
*
*/
{

/**
*main
*@paramargs
*/
publicstaticvoidmain(String[]args){
StringfilePath="d:\out2.txt";
write(filePath);
read(filePath);
}

/**
*Read
*@paramfilePathfilepath
*/
publicstaticvoidread(StringfilePath){
FileReaderfr=null;
StringBuilderresult=newStringBuilder();
;
try{
fr=newFileReader(newFile(filePath));
char[]charArray=newchar[1024];
while(fr.read(charArray)!=-1){
result.append(charArray);
}
}catch(FileNotFoundExceptione){
e.printStackTrace();
}catch(IOExceptione){
//TODOAuto-generatedcatchblock
e.printStackTrace();
}
if(fr!=null){
try{
fr.close();
}catch(IOExceptione){
e.printStackTrace();
}
}
System.out.println(result.toString());
}


/**
*Write
*@paramfilePathfilepath
*/
publicstaticvoidwrite(StringfilePath){
FileWriterfw=null;
try{
fw=newFileWriter(newFile(filePath));
for(inti=1;i<=50;i++){
fw.append(String.valueOf(i));
}
fw.flush();
}catch(IOExceptione){
e.printStackTrace();
}
if(fw!=null){
try{
fw.close();
}catch(IOExceptione){
e.printStackTrace();
}
}
}
}

⑧ java中位元組流讀寫和字元流讀寫怎麼理解

位元組流與字元流主要的區別是他們的的處理方式
位元組流是最基本的,所有的InputStream和OutputStream的子類都是,主要用在處理二進制數據,它是按位元組來處理的
但實際中很多的數據是文本,又提出了字元流的概念,它是按虛擬機的encode來處理,也就是要進行字元集的轉化
這兩個之間通過 InputStreamReader,OutputStreamWriter來關聯,實際上是通過byte[]和String來關聯
在實際開發中出現的漢字問題實際上都是在字元流和位元組流之間轉化不統一而造成的

在從位元組流轉化為字元流時,實際上就是byte[]轉化為String時,
public String(byte bytes[], String charsetName)
有一個關鍵的參數字元集編碼,通常我們都省略了,那系統就用操作系統的lang
而在字元流轉化為位元組流時,實際上是String轉化為byte[]時,
byte[] String.getBytes(String charsetName)
也是一樣的道理

⑨ java的幾種IO流讀取文件方式

一、超類:


位元組流: InputStream(讀入流) OutputStream(寫出流)


字元流: Reader(字元 讀入流) Writer (字元寫出流)

二、文件操作流


位元組流: FileInputStream ,FileOutputStream


字元流: FileReader, FileWriter(用法與位元組流基本相同,不寫)

//1.指定要讀 的文件目錄及名稱


File file =new File("文件路徑");


//2.創建文件讀入流對象


FileInputStream fis =new FileInputStream(file);


//3.定義結束標志,可用位元組數組讀取


int i =0 ;


while((i = fis.read())!=-1){


//i 就是從文件中讀取的位元組,讀完後返回-1


}


//4.關閉流


fis.close();


//5.處理異常

//1.指定要寫到的文件目錄及名稱


File file =new File("文件路徑");


//2.創建文件讀入流對象


FileOutputStream fos =new FileOutputStream(file);


//3.定義結束標志


fos.write(要寫出的位元組或者位元組數組);


//4.刷新和關閉流


fos.flush();


fos.close();


//5.處理異常

三、緩沖流:


位元組緩沖流: BufferedInputStream,BufferedOutputStream


字元緩沖流:BufferedReader ,BufferedWriter


緩沖流是對流的操作的功能的加強,提高了數據的讀寫效率。既然緩沖流是對流的功能和讀寫效率的加強和提高,所以在創建緩沖流的對象時應該要傳入要加強的流對象。

//1.指定要讀 的文件目錄及名稱


File file =new File("文件路徑");


//2.創建文件讀入流對象


FileInputStream fis =new FileInputStream(file);


//3.創建緩沖流對象加強fis功能


BufferedInputStream bis =new BufferedInputStream(fis);


//4.定義結束標志,可用位元組數組讀取


int i =0 ;


while((i = bis.read())!=-1){


//i 就是從文件中讀取的位元組,讀完後返回-1


}


//5.關閉流


bis.close();


//6.處理異常

//1.指定要寫到的文件目錄及名稱


File file =new File("文件路徑");


//2.創建文件讀入流對象


FileOutputStream fos =new FileOutputStream(file);


//3.創建緩沖流對象加強fos功能


BufferedOutputStream bos=new BufferedOutputStream(fos);


//4.向流中寫入數據


bos.write(要寫出的位元組或者位元組數組);


//5.刷新和關閉流


bos.flush();


bos.close();


//6.處理異常

四、對象流


ObjectInputStream ,ObjectOutputStream


不同於以上兩種類型的流這里只能用位元組對對象進行操作原因可以看上篇的編碼表比照原理

ObjectOutputStream對象的序列化:


將java程序中的對象寫到本地磁碟里用ObjectOutputStream


eg:將Person類的對象序列化到磁碟

  1. 創建Person類


    注1:此類要實現Serializable介面,此介面為標志性介面


    注2:此類要有無參的構造函數


    注3:一旦序列化此類不能再修改


    class Person implements Serializable{


    public Person(){}


    }


    2.創建對象流對象


    註:要增強功能可以將傳入文件緩沖流


    ObjectOutputStream oos =new ObjectOutputStream(


    new FileOutputStream(new File("文件路徑")));


    3.寫入對象 ,一般會將對象用集合存儲起來然後直接將集合寫入文件


    List<Person> list =new ArrayList<>();


    list.add(new Person());


    ...(可以添加多個)


    oos.writeObject(list);


    4.關閉流,處理異常


    oos.flush();


    oos.close();

五、轉換流:

這類流是用於將字元轉換為位元組輸入輸出,用於操作字元文件,屬於字元流的子類,所以後綴為reader,writer;前綴inputstream,outputstream;

注 :要傳入位元組流作為參賽


InputStreamReader: 字元轉換輸出流


OutputStreamWriter:字元轉換輸入流

//1.獲取鍵盤輸入的位元組流對象

inInputStream in =Stream.in;

/*2.用轉換流將位元組流對象轉換為字元流對象,方便調用字元緩沖流的readeLine()方法*/


InputStreamReader isr =new InputStreamReader(in);


/*5.創建字元轉換輸出流對象osw,方便把輸入的字元流轉換為位元組輸出到本地文件。*/


OutputStreamWriter osw =new OutputStreamWriter(new
FileOutputStream(new File("文件名")));



/*3.現在isr是字元流,可以作為參數傳入字元緩沖流中*/


BufferedReader br =new BufferedReader(isr);

/*4.可以調用字元緩沖流br的readLine()方法度一行輸入文本*/


String line =null;


while((line =br.readLine()){


osw.write(line);//osw是字元流對象,可以直接操作字元串

}



註:InputStreamReader isr =new InputStreamReader(new "各種類型的位元組輸入流都行即是:後綴為InputStream就行");


OutputStreamWriter osw =new OutputStreamWriter(new
"後綴為OutputStream就行");

六、區別記憶


1.對象流是可以讀寫幾乎所有類型的只要是對象就行,而位元組字元流,只能讀寫單個位元組字元或者位元組字元數組,以上沒有讀寫位元組字元數組的;注意對象流只有位元組流!


2.字元和位元組循環讀入的結束條件int i=0; (i =fis.read())!=-1
用字元數組復制文件(fr 讀入流 ,fw寫出流),位元組流也是相同的用法

int i = 0; char[] c = new char[1024];


while((i = fr.reade()) !=-1)){


fw.write(c,0,i);


}

123456

3.對象流裡面套緩沖流的情景:


new ObjectInputStream(new BufferedInputStream(new FileInputStream(new File(「文件路徑」))));

4.記憶流及其功能的方法:


前綴表示功能,後綴表示流的類型;


比如說FileInputStream 前綴:File,表示操作的磁碟,後綴:intputstream,表示是位元組輸入流。


同理 FileReader:表示操作文件的字元流


ObjectInputStream :操作對象的位元組輸入流

5.拓展:獲取鍵盤輸入的字元的緩沖流的寫法:


new BufferedReader(new InputStreamReader(System.in)));


將位元組以字元形式輸出到控制台的字元緩沖流的寫法:


new BufferedWriter( new OutputStreamWriter(System.out))

⑩ java位元組流 一次可以讀一行 字元流 一次讀一個是嗎

JAVA位元組流 是每次從文件中讀取單個位元組 字元流是每次讀出1個字元 相當於每次讀出2個位元組
FileInputStream fs=new FileInputStream(路徑); 這是一個字元流
InputStreamReader ir=new InputStreamReader( fs) 這是一個字元流 fs 為位元組流 這個類就是把位元組流轉化為字元流;
字元流 就是為了方便讀取文字和符號的 都知道中文漢字要2個位元組才能存儲 如果一次讀出1個位元組 在轉化為中文 就會出亂碼了 ;
這些問題你都可以通過查詢API文檔找到答案的

閱讀全文

與java字元流讀取相關的資料

熱點內容
皓強工具解壓步驟 瀏覽:688
部隊抗洪搶險命令範文 瀏覽:886
歐姆龍plc編程軟體使用教程 瀏覽:592
ai文件pdf 瀏覽:911
騰訊雲伺服器掛載混合雲 瀏覽:758
智能小車用什麼單片機 瀏覽:463
java怎麼給窗口關閉 瀏覽:940
列舉51單片機的定址方式 瀏覽:706
剪輯app怎麼寫長篇文字 瀏覽:400
app專屬流量過月租怎麼不更新 瀏覽:654
王者程序員都有誰 瀏覽:76
給牛換腳掌解壓 瀏覽:387
圍棋有多少種演算法 瀏覽:602
unity資源包在哪個文件夾 瀏覽:704
阿里雲伺服器遠程鏈接不成功 瀏覽:482
文件系統pdf 瀏覽:766
原神安卓區服什麼意思 瀏覽:37
貝殼app怎麼線上發布 瀏覽:160
如何挑選安卓系統機頂盒 瀏覽:54
安卓快充使用有什麼注意事項 瀏覽:910