導航:首頁 > 編程語言 > java讀取文件位元組流

java讀取文件位元組流

發布時間:2023-04-01 20:54:08

java怎麼實現讀取一個文件,拿到二進制流

Java讀取二進制文件,以位元組為單位進行讀取,還可讀取圖片、音樂文件、視頻文件等,
在Java中,提供了四種類來對文件進行操作,分別是InputStream OutputStream Reader Writer ,前兩種是對位元組流的操作,後兩種則是對字元流的操作。
示例代碼如下:
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;
}

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

Java字元流是處理字元(Char)對象用的,位元組流是處理位元組(Byte)對象用的。處理的目標對象不同,處理方法也就不一樣了。

字元流處理的基本單位是字元(Java中的字元是16位的),輸入流以Reader為基礎,輸出流以Writer為基礎;
位元組流的基本單位是位元組(Java中的位元組是8位的),輸入流以 InputStream為基礎,輸出流以 OutputStream為基礎;

字元流在輸入時可以按字元讀取,也可以按行讀取,會去掉回車換行,常用於讀取字元數據;
而位元組流按位元組讀取,不作任何處理,常用於讀取二進制數據。

Java中的字元在內部都是使用Unicode進行表示的,因此,要正確讀取字元數據,需要知道字元的編碼字元集,字元流提供編碼字元集的指定,如果不指定使用系統默認的方式對字元數據進行編碼轉換,這個編碼字元集不正確,會造成讀進來的地字元出現亂碼。

位元組流雖然是讀取二進制數據用的,但也可以讀取字元文件,按位元組進行處理,讀進來之後可以根據編碼字元集進行轉換,也可以變成字元串。

❸ java位元組流怎麼讀取數據

packagetest;

importjava.io.File;
importjava.io.FileInputStream;
importjava.io.IOException;
importjava.io.InputStream;

publicclassStreamTest{
publicstaticvoidmain(String[]args)throwsIOException{
//定義讀入流
InputStreamis=newFileInputStream(newFile("文件名"));
//定義緩沖區
byte[]buffer=newbyte[1024];
//讀取
is.read(buffer);
//關閉流
is.close();
}
}

希望能幫到你。

❹ java文件如何讀取

java讀取文件方法大全
一、多種方式讀文件內容。

1、按位元組讀取文件內容
2、按字元讀取文件內容
3、按行讀取文件內容
4、隨機讀取文件內容
Java代碼
1. import java.io.BufferedReader;
2. import java.io.File;
3. import java.io.FileInputStream;
4. import java.io.FileReader;
5. import java.io.IOException;
6. import java.io.InputStream;
7. import java.io.InputStreamReader;
8. import java.io.RandomAccessFile;
9. import java.io.Reader;
10.
11. public class ReadFromFile {
12. /**
13. * 以位元組為單位讀取文件,常用於讀二進制文件,如圖片、聲音、影像等文件。
14. *
15. * @param fileName
16. * 文件的名
17. */
18. public static void readFileByBytes(String fileName) {
19. File file = new File(fileName);
20. InputStream in = null;
21. try {
22. System.out.println("以位元組為單位讀取文件內容,一次讀一個位元組:");
23. // 一次讀一個位元組
24. in = new FileInputStream(file);
25. int tempbyte;
26. while ((tempbyte = in.read()) != -1) {
27. System.out.write(tempbyte);
28. }
29. in.close();
30. } catch (IOException e) {
31. e.printStackTrace();
32. return;
33. }
34. try {
35. System.out.println("以位元組為單位讀取文件內容,一次讀多個位元組:");
36. // 一次讀多個位元組
37. byte[] tempbytes = new byte[100];
38. int byteread = 0;
39. in = new FileInputStream(fileName);
40. ReadFromFile.showAvailableBytes(in);
41. // 讀入多個位元組到位元組數組中,byteread為一次讀入的位元組數
42. while ((byteread = in.read(tempbytes)) != -1) {
43. System.out.write(tempbytes, 0, byteread);
44. }
45. } catch (Exception e1) {
46. e1.printStackTrace();
47. } finally {
48. if (in != null) {
49. try {
50. in.close();
51. } catch (IOException e1) {
52. }
53. }
54. }
55. }
56.
57. /**
58. * 以字元為單位讀取文件,常用於讀文本,數字等類型的文件
59. *
60. * @param fileName
61. * 文件名
62. */
63. public static void readFileByChars(String fileName) {
64. File file = new File(fileName);
65. Reader reader = null;
66. try {
67. System.out.println("以字元為單位讀取文件內容,一次讀一個位元組:");
68. // 一次讀一個字元
69. reader = new InputStreamReader(new FileInputStream(file));
70. int tempchar;
71. while ((tempchar = reader.read()) != -1) {
72. // 對於windows下,\r\n這兩個字元在一起時,表示一個換行。
73. // 但如果這兩個字元分開顯示時,會換兩次行。
74. // 因此,屏蔽掉\r,或者屏蔽\n。否則,將會多出很多空行。
75. if (((char) tempchar) != '\r') {
76. System.out.print((char) tempchar);
77. }
78. }
79. reader.close();
80. } catch (Exception e) {
81. e.printStackTrace();
82. }
83. try {
84. System.out.println("以字元為單位讀取文件內容,一次讀多個位元組:");
85. // 一次讀多個字元
86. char[] tempchars = new char[30];
87. int charread = 0;
88. reader = new InputStreamReader(new FileInputStream(fileName));
89. // 讀入多個字元到字元數組中,charread為一次讀取字元數
90. while ((charread = reader.read(tempchars)) != -1) {
91. // 同樣屏蔽掉\r不顯示
92. if ((charread == tempchars.length)
93. && (tempchars[tempchars.length - 1] != '\r')) {
94. System.out.print(tempchars);
95. } else {
96. for (int i = 0; i < charread; i++) {
97. if (tempchars[i] == '\r') {
98. continue;
99. } else {
100. System.out.print(tempchars[i]);
101. }
102. }
103. }
104. }
105.
106. } catch (Exception e1) {
107. e1.printStackTrace();
108. } finally {
109. if (reader != null) {
110. try {
111. reader.close();
112. } catch (IOException e1) {
113. }
114. }
115. }
116. }
117.
118. /**
119. * 以行為單位讀取文件,常用於讀面向行的格式化文件
120. *
121. * @param fileName
122. * 文件名
123. */
124. public static void readFileByLines(String fileName) {
125. File file = new File(fileName);
126. BufferedReader reader = null;
127. try {
128. System.out.println("以行為單位讀取文件內容,一次讀一整行:");
129. reader = new BufferedReader(new FileReader(file));
130. String tempString = null;
131. int line = 1;
132. // 一次讀入一行,直到讀入null為文件結束
133. while ((tempString = reader.readLine()) != null) {
134. // 顯示行號
135. System.out.println("line " + line + ": " + tempString);
136. line++;
137. }
138. reader.close();
139. } catch (IOException e) {
140. e.printStackTrace();
141. } finally {
142. if (reader != null) {
143. try {
144. reader.close();
145. } catch (IOException e1) {
146. }
147. }
148. }
149. }
150.
151. /**
152. * 隨機讀取文件內容
153. *
154. * @param fileName
155. * 文件名
156. */
157. public static void readFileByRandomAccess(String fileName) {
158. RandomAccessFile randomFile = null;
159. try {
160. System.out.println("隨機讀取一段文件內容:");
161. // 打開一個隨機訪問文件流,按只讀方式
162. randomFile = new RandomAccessFile(fileName, "r");
163. // 文件長度,位元組數
164. long fileLength = randomFile.length();
165. // 讀文件的起始位置
166. int beginIndex = (fileLength > 4) ? 4 : 0;
167. // 將讀文件的開始位置移到beginIndex位置。
168. randomFile.seek(beginIndex);
169. byte[] bytes = new byte[10];
170. int byteread = 0;
171. // 一次讀10個位元組,如果文件內容不足10個位元組,則讀剩下的位元組。
172. // 將一次讀取的位元組數賦給byteread
173. while ((byteread = randomFile.read(bytes)) != -1) {
174. System.out.write(bytes, 0, byteread);
175. }
176. } catch (IOException e) {
177. e.printStackTrace();
178. } finally {
179. if (randomFile != null) {
180. try {
181. randomFile.close();
182. } catch (IOException e1) {
183. }
184. }
185. }
186. }
187.
188. /**
189. * 顯示輸入流中還剩的位元組數
190. *
191. * @param in
192. */
193. private static void showAvailableBytes(InputStream in) {
194. try {
195. System.out.println("當前位元組輸入流中的位元組數為:" + in.available());
196. } catch (IOException e) {
197. e.printStackTrace();
198. }
199. }
200.
201. public static void main(String[] args) {
202. String fileName = "C:/temp/newTemp.txt";
203. ReadFromFile.readFileByBytes(fileName);
204. ReadFromFile.readFileByChars(fileName);
205. ReadFromFile.readFileByLines(fileName);
206. ReadFromFile.readFileByRandomAccess(fileName);
207. }
208. }

二、將內容追加到文件尾部
1. import java.io.FileWriter;
2. import java.io.IOException;
3. import java.io.RandomAccessFile;
4.
5. /**
6. * 將內容追加到文件尾部
7. */
8. public class AppendToFile {
9.
10. /**
11. * A方法追加文件:使用RandomAccessFile
12. * @param fileName 文件名
13. * @param content 追加的內容
14. */
15. public static void appendMethodA(String fileName, String content) {
16. try {
17. // 打開一個隨機訪問文件流,按讀寫方式
18. RandomAccessFile randomFile = new RandomAccessFile(fileName, "rw");
19. // 文件長度,位元組數
20. long fileLength = randomFile.length();
21. //將寫文件指針移到文件尾。
22. randomFile.seek(fileLength);
23. randomFile.writeBytes(content);
24. randomFile.close();
25. } catch (IOException e) {
26. e.printStackTrace();
27. }
28. }
29.
30. /**
31. * B方法追加文件:使用FileWriter
32. * @param fileName
33. * @param content
34. */
35. public static void appendMethodB(String fileName, String content) {
36. try {
37. //打開一個寫文件器,構造函數中的第二個參數true表示以追加形式寫文件
38. FileWriter writer = new FileWriter(fileName, true);
39. writer.write(content);
40. writer.close();
41. } catch (IOException e) {
42. e.printStackTrace();
43. }
44. }
45.
46. public static void main(String[] args) {
47. String fileName = "C:/temp/newTemp.txt";
48. String content = "new append!";
49. //按方法A追加文件
50. AppendToFile.appendMethodA(fileName, content);
51. AppendToFile.appendMethodA(fileName, "append end. \n");
52. //顯示文件內容
53. ReadFromFile.readFileByLines(fileName);
54. //按方法B追加文件
55. AppendToFile.appendMethodB(fileName, content);
56. AppendToFile.appendMethodB(fileName, "append end. \n");
57. //顯示文件內容
58. ReadFromFile.readFileByLines(fileName);
59. }
60. }

❺ 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的幾種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如何讀取txt文件

java讀取txt文件內容。可以作如下理解:

1、首先獲得一個文件句柄。File file = new File(); file即為文件句柄。兩人之間連通電話網路了。接下來可以開始打電話了。

2、通過這條線路讀取甲方的信息:new FileInputStream(file) 目前這個信息已經讀進來內存當中了。接下來需要解讀成乙方可以理解的東西

3、既然你使用了FileInputStream()。那麼對應的需要使用InputStreamReader()這個方法進行解讀剛才裝進來內存當中的數據

4、解讀完成後要輸出呀。那當然要轉換成IO可以識別的數據呀。那就需要調用位元組碼讀取的方法BufferedReader()。同時使用bufferedReader()的readline()方法讀取txt文件中的每一行數據哈。


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 碼農小江
* H20121012.java
* 2012-10-12下午11:40:21
*/
public class H20121012 {
/**
* 功能:Java讀取txt文件的內容
* 步驟:1:先獲得文件句柄
* 2:獲得文件句柄當做是輸入一個位元組碼流,需要對這個輸入流進行讀取
* 3:讀取到輸入流後,需要讀取生成位元組流
* 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("讀取文件內容出錯");
e.printStackTrace();
}

}

public static void main(String argv[]){
String filePath = "L:\Apache\htdocs\res\20121012.txt";
// "res/";
readTxtFile(filePath);
}}
閱讀全文

與java讀取文件位元組流相關的資料

熱點內容
老濕機免費看片網站 瀏覽:914
ck影院 瀏覽:942
ubuntuphpfpm安裝 瀏覽:414
末世之一女多男 瀏覽:178
電腦上如何下載稅務app 瀏覽:528
s曲線單片機 瀏覽:664
配音秀app如何自動取消續費功能 瀏覽:755
程序員深山養雞 瀏覽:825
類似渣夫的百惠媳的小說 瀏覽:502
javaforever 瀏覽:637
女主叫桃子的微電影 瀏覽:449
藍光超清1080p影視 瀏覽:296
男變女懷孕並生孩子的小說 瀏覽:344
安卓怎麼玩出蘋果的軟體 瀏覽:92
除了80以外還有啥看電影 瀏覽:369
加密分享可以採用的演算法 瀏覽:686
請問誰有免費的男人網站? 瀏覽:75
58pdf 瀏覽:768
年輕人愛看的免費的電影網站 瀏覽:782
天津水游城電影院今日影訊簡介 瀏覽:99