java以字节流形式读写文件
java中以字节流的形式读取文件采用的是FileInputStream,将指定路径的文件以字节数组的形式循环读取,代码如下:
public static void ReadFileByByte(){
String path="H:\\bbb\\aa\\tt.txt";
FileInputStream fis = null;
try {
int length = 0;
byte[] Buff = new byte[1024];
File file = new File(path);
fis = new FileInputStream(file);
while((length =fis.read(Buff))!=-1){
//对Buff进行处理
System.out.println(new String(Buff));
}
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}catch (IOException ex) {
// TODO Auto-generated catch block
ex.printStackTrace();
}finally{
if(fis!=null){
try {
fis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
java中以字节流的形式写入文件采用的是FileOutputStream,在指定路径下写入指定字节数组内容,并可设定追加模式或者覆盖模式,代码如下:
/**
* 读取指定文件数据写入另一个文件
* <p>
* <p>
* <p>
* 字节数组缓冲
*/
public static void readOldFileWriteNewFileTwo() {
File oldFile = new File("E:\\Java\\Hydrangeas.jpg"); //237 109
File newFile = new File("E:\\Java\\newpic.jpg");
FileInputStream fis = null;
FileOutputStream fos = null;
try {
fis = new FileInputStream(oldFile); // 文件字节输入流
fos = new FileOutputStream(newFile); // 文件字节输出流
byte[] bytes = new byte[128]; //缓冲
int len;
while ((len = fis.read(bytes)) != -1) {
fos.write(bytes, 0, len);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (fis != null)
fis.close();
if (fos != null)
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
/**
* 读取指定文件数据写入另一个文件
*/
public static void readOldFileWriteNewFile() {
File oldFile = new File("H:\\bbb\\aa\\tt.txt");
File newFile = new File("H:\\bbb\\aa\\t2.txt");
FileInputStream fis = null;
FileOutputStream fos = null;
try {
fis = new FileInputStream(oldFile); // 文件字节输入流
fos = new FileOutputStream(newFile); // 文件字节输出流
int count = 0;
int b;
while ((b = fis.read()) != -1) {
fos.write(b);
count++;
}
System.out.println("count :" + count);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (fis != null)
fis.close();
if (fos != null)
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
/**
* 写字符串数据到文件
*/
public static void writeFileOne() {
String s = "创建一个向指定 File 对象表示的文件中写入数据的文件输出流";
// 第一步 创建文件
File file = new File("E:\\Java\\demo.txt");
FileOutputStream fos = null;
try {
// 第二步 创建文件字节输出流
fos = new FileOutputStream(file, true); // 第二参数据为true,表示字节写入文件末尾处
// 第三步 写数据到字节输出流
byte[] b = s.getBytes(); // 字符串转字节数组
fos.write(b);
} catch (IOException io) {
System.out.println(io.getMessage());
} finally {
// 第四步 关闭流
try {
if (fos != null)
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}

