导航:首页 > 编程语言 > 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相关的资料

热点内容
python操作zookeeper 浏览:705
苹果手机dcim文件夹显示不出来 浏览:430
如何压缩文件夹联想电脑 浏览:583
程序员的学习之旅 浏览:440
apkdb反编译 浏览:922
雪花算法为什么要二进制 浏览:825
在文档中打开命令行工具 浏览:608
android图标尺寸规范 浏览:369
python实用工具 浏览:208
流量计pdf 浏览:936
科东加密认证价格 浏览:532
dos命令读文件 浏览:996
成为程序员需要什么学历 浏览:672
pdf农药 浏览:228
canal加密 浏览:497
日本安卓系统和中国有什么区别 浏览:137
linux命令行修改文件 浏览:838
从编译和解释的角度看 浏览:649
徐志摩pdf 浏览:651
夏天解压球视频 浏览:304