java怎么用read()每次读文件中的四个字节保存在数组中

如题所述

java使用read()方法进行读文件中的四个字节保存在数组总的示例如下:


public static void main(String[] arg) throws Exception {
BufferedReader reader = new BufferedReader(new FileReader("E:/test.txt"));
int[] list = new int[20];
int i = 0;
String line = null;
while ((line = reader.readLine()) != null) {
String[] vStrs = line.split(" ");
for (String str : vStrs) {
list[i++] = Integer.parseInt(str);
}
}
System.out.println(Arrays.toString(list));
}
温馨提示:答案为网友推荐,仅供参考
第1个回答  2012-03-24
File file = new File(fileName);
try {
BufferedInputStream bufferInput = new BufferedInputStream(new FileInputStream(file));
char[] ch = new char[4];
int i = 0;
while ((ch[i] = bufferInput.read())!=-1) {
i++;
if(i == 4){ //当有四个字节保存在数组中则输出
i = 0;
System.out.println(ch);//你也可以把 ch 转成String 再赋给你创建的数组。
}
}
bufferInput.close();
} catch (Exception e) {
e.printStackTrace();
}
第2个回答  推荐于2017-09-16
//创建文件流对象
File f = new File("E:\\a.txt");

//创建读取流对象
FileReader fr = new FileReader(f);
//创建加速器
BufferedReader bfr = new BufferedReader(fr);

String str="";
//循环读取
while(str !=null){
//行读取
str = bfr.readLine();
System.out.println(str);
}

//字节流取文件
File f = new File("E:\\a.txt");
//创建读取流对象
FileInputStream fin = new FileInputStream(f);

byte b[] = new byte[1024];

int count =0;

while((count = fin.read(b))>0){

System.out.println(count);
//字符转换 string 和 byte
String s = new String(b,0,count);
System.out.println(s);

}
fin.close();
///例子
package com.lilina.aa;

public class Eg1 {
public static void main(String[] args) throws Exception {

//文字流

//创建对象
FileInputStream fl = new FileInputStream("e:\\Hydrangeas.jpg");
FileOutputStream fo = new FileOutputStream("c:\\Hydrangeas.jpg");
int count=0;
byte b[]=new byte[1024];
//循环读取
while((count=fl.read(b))>0){

fo.write(b, 0, count);

}
//关闭
fl.close();
fo.close();
}
}追问

我现在要新建一个自己的数组来保存读取的数据,这些数据是每四个字节一个数据的,请问我该怎么读取和保存在我自己的数组中,。。。。。。。急人啊。。。。谢谢。

追答

边读边写进文件 再循环的时候

本回答被提问者采纳
第3个回答  2012-03-24
File file = new File(fileName);
try {
BufferedInputStream bufferInput = new BufferedInputStream(new FileInputStream(file));
int temp = 0;
while ((temp=bufferInput.read())!=-1) {
System.out.print(temp);
}
bufferInput.close();
} catch (Exception e) {
e.printStackTrace();
}
第4个回答  2012-04-06
//缓冲
byte[] data = new byte[4];
//读取
int len = read(data);
while(len==4){
len = read(data);
//其他处理
}
相似回答