導航:首頁 > 編程語言 > java讀取文件byte

java讀取文件byte

發布時間:2022-05-05 12:08:32

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讀取文件時,InputStream的read(byte[])方法的byte[]的長度不知如何設置,請教大蝦們

那個長度應該只是緩沖區而已,應該不影響結果的。我做的時候一般都設置為1024,即1KB
這個是我部分的成功代碼
inputStream = new BufferedInputStream(new FileInputStream(
downloadFile));
outputStream = new BufferedOutputStream(response
.getOutputStream());
byte[] buffer = new byte[1024];
int readIndex;
while (-1 != (readIndex = inputStream.read(buffer, 0,
buffer.length))) {
outputStream.write(buffer, 0, readIndex);
}

❸ java讀取二進制文件

思路:按照位元組讀取文件到緩沖,然後對文件內容進行處理。

代碼如下:


publicstaticvoidreadFile()throwsIOException{
RandomAccessFilef=newRandomAccessFile("test.txt","r");
byte[]b=newbyte[(int)f.length()];
//將文件按照位元組方式讀入到位元組緩存中
f.read(b);
//將位元組轉換為utf-8格式的字元串
Stringinput=newString(b,"utf-8");
//可以匹配到所有的數字
Patternpattern=Pattern.compile("\d+(\.\d+)?");
Matchermatch=pattern.matcher(input);
while(match.find()){
//match.group(0)即為你想獲取的數據
System.out.println(match.group(0));
}
f.close();
}

❹ java中怎樣按位元組讀取文件並復制到另一個文件夾

這里以位元組流FileInputStream,FileOutputStream為例。代碼例子如下:

importjava.io.File;
/**
*把一個文件夾中的文件復制到一個指定的文件夾
*@authoryoung
*
*/
importjava.io.FileInputStream;
importjava.io.FileNotFoundException;
importjava.io.FileOutputStream;
importjava.io.IOException;

publicclassCopyFile{
publicstaticvoidmain(String[]args){
/*指定源exe文件的存放路徑*/
Stringstr="f:/jdk-1_5_0_06-windows-i586-p.exe";
/*指定復制後的exe的目標路徑*/
Stringstrs="e:/.exe";
/*創建輸入和輸出流*/
FileInputStreamfis=null;
FileOutputStreamfos=null;

try{
/*將io流和文件關聯*/
fis=newFileInputStream(str);

fos=newFileOutputStream(strs);
byte[]buf=newbyte[1024*1024];
intlen;
while((len=fis.read(buf))!=-1){
fos.write(buf,0,len);

}
}catch(FileNotFoundExceptione){
//TODOAuto-generatedcatchblock
e.printStackTrace();
}catch(IOExceptione){
//TODOAuto-generatedcatchblock
e.printStackTrace();
}finally{
try{
fis.close();
fos.close();
}catch(IOExceptione){
//TODOAuto-generatedcatchblock
e.printStackTrace();
}
}
}
}

❺ JAVA 讀文件一定得創建byte數組為什麼

看情況吧...
當然你心情好了可以一個位元組一個位元組的讀;
為什麼要用byte,其實java讀寫文件調用的依然是底層操作系統的介面.
在操作系統層面數據時按照塊來讀的.
申請byte數組的目的是在jvm中開辟一塊空間,然後調用jvm操作指令,jvm根據指令告訴操作系統,把這塊數據給我填滿.操作系統填滿之後,java就返回了.

為什麼要用byte?因為byte是數據存儲的最小單位了.
所以byte[]數組就是一次性讀取多少個最小單位,然後返回.

這只是簡單的描述,要更詳細的了解,建議讀java language specification (jls),jls3好像是1.5,1.6的jls7是jdk1.7的.還有就是操作系統原理相關的書.
只能回答這么多了,再深的我也不懂~

❻ 用java如何讀取一個文件的指定位元組位置的數據

可以使用RandomAccessFile類。例如要從100位元組開始輸出工作目錄下的data.txt文件的類容。
package konw.test1;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.RandomAccessFile;
public class Test1
{
public static void main(String[] args)
{
long pos = 100;
try
{
String str = "";
RandomAccessFile randomAccessFile = new RandomAccessFile("data.txt", "rw");
randomAccessFile.seek(pos);//將文件流的位置移動到pos位元組處
while( (str = randomAccessFile.readLine()) != null)
{
System.out.println(str);
}
randomAccessFile.close();

} catch (FileNotFoundException e)
{
e.printStackTrace();
} catch (IOException e)
{
e.printStackTrace();
}
}
}

❼ java file 獲取文件大小 是什麼單位

1、java file 獲取文件大小 ,單位是kb,File.length()獲得文件位元組大小/1024 獲得 KB數, 由於整數運算省略小數部分,故加1。

2、目前Java獲取文件大小的方法有兩種:

1)通過file的length()方法獲取。

2)通過流式方法獲取。

❽ 請問java輸入流中當文件大於byte數組長度的時候,該如何循環讀取

byte[]data=newbyte[1024];
intlen=fis.read(data);
//循環將文件fileText.txt中的內容讀取到位元組數組中
StringBuildersb=newStringBuilder();
sb.append(newString(data,0,len));
while(len!=-1){
len=fis.read(data);
if(len!=-1){
sb.append(newString(data,0,len));
}
}
System.out.println(sb);

❾ java中如何讀取某個文件的某個位元組看清具體要求

RandomAccessFile類

public class RandomAccessFile extends Object implements DataOutput, DataInput, Closeable
此類的實例支持對隨機訪問文件的讀取和寫入。隨機訪問文件的行為類似存儲在文件系統中的一個大型 byte
數組。存在指向該隱含數組的游標或索引,稱為文件指針;輸入操作從文件指針開始讀取位元組,並隨著對位元組的讀取而前移此文件指針。如果隨機訪問文件以讀取/寫入模式創建,則輸出操作也可用;輸出操作從文件指針開始寫入位元組,並隨著對位元組的寫入而前移此文件指針。寫入隱含數組的當前末尾之後的輸出操作導致該數組擴展。該文件指針可以通過
getFilePointer 方法讀取,並通過 seek 方法設置。

public void seek(long pos)
throws IOException設置到此文件開頭測量到的文件指針偏移量,在該位置發生下一個讀取或寫入操作。偏移量的設置可能會超出文件末尾。偏移量的設置超出文件末尾不會改變文件的長度。只有在偏移量的設置超出文件末尾的情況下對文件進行寫入才會更改其長度。

參數:pos - 從文件開頭以位元組為單位測量的偏移量位置,在該位置設置文件指針。
拋出:IOException - 如果
pos 小於 0 或者發生 I/O 錯誤。

❿ java怎麼讀取和寫入位元組文件開發環境 MyEclipse 8.6

InputStream
三個基本的讀方法
abstract
int
read()

讀取一個位元組數據,並返回讀到的數據,如果返回-1,表示讀到了輸入流的末尾。
int
read(byte[]
b)

將數據讀入一個位元組數組,同時返回實際讀取的位元組數。如果返回-1,表示讀到了輸入流的末尾。
int
read(byte[]
b,
int
off,
int
len)
:將數據讀入一個位元組數組,同時返回實際讀取的位元組數。如果返回-1,表示讀到了輸入流的末尾。off指定在數組b中存放數據的起始偏移位置;len指定讀取的最大位元組數。
OutputStream
三個基本的寫方法
abstract
void
write(int
b)
:往輸出流中寫入一個位元組。
void
write(byte[]
b)
:往輸出流中寫入數組b中的所有位元組。
void
write(byte[]
b,
int
off,
int
len)
:往輸出流中寫入數組b中從偏移量off開始的len個位元組的數據。
其它方法
void
flush()
:刷新輸出流,強制緩沖區中的輸出位元組被寫出。
void
close()
:關閉輸出流,釋放和這個流相關的系統資源。

閱讀全文

與java讀取文件byte相關的資料

熱點內容
安卓qq郵箱格式怎麼寫 瀏覽:429
如何電信租用伺服器嗎 瀏覽:188
編程中計算根號的思維 瀏覽:181
可愛的程序員16集背景音樂 瀏覽:446
軟體代碼內容轉換加密 瀏覽:795
什麼app看電視不要錢的 瀏覽:16
烏班圖怎麼安裝c語言編譯器 瀏覽:278
plc通訊塊編程 瀏覽:923
我的世界伺服器怎麼清地皮 瀏覽:421
ftp伺服器如何批量改名 瀏覽:314
網易我的世界伺服器成員如何傳送 瀏覽:268
公司雲伺服器遠程訪問 瀏覽:633
法哲學pdf 瀏覽:637
清大閱讀app是什麼 瀏覽:447
怎麼用qq瀏覽器整體解壓文件 瀏覽:585
肺組織壓縮15 瀏覽:270
安卓手機為什麼換電話卡沒反應 瀏覽:797
諸子集成pdf 瀏覽:339
php注冊框代碼 瀏覽:717
手機加密好還是不加好好 瀏覽:815