java文件的字节输入流与输出流
输入和输出相对与程序而言简单的理解就是:将硬盘已有的数据读取到内存中的是输入流,将内存中的数据存储到硬盘中的就是输出流。
字节流:每次操作对对象单位是字节的输入或者输出,最常用的FileInputStream和FileOutputStream两个字节流的子类,其中FileInputStream是输入流,FileOutputStream是输出流
字节的输入流 FileInputStream
下面展示一些 内联代码片
。
// 给了一个[1024*1]的字节流
// byte[] arr = new byte[1024 * 1];
//这样可以加大流的输入,不用一个一个的字节输入加快输入速率
public static void main(String[] args) {
// 创建输入流FileInputStream
FileInputStream fileInput = null;
try {
// 创建文件地址
fileInput = new FileInputStream("E:\\ccw.txt");
// 给定一个字节大小
// 每一次读取的时候就可以按照这个字节流输入
byte[] arr = new byte[1024 * 1];// 给了一个[1024*1]的字节流
int len = 0;
while ((len = fileInput.read(arr)) != -1) {
String str = new String(arr, 0, len);
System.out.println(str);
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
// 判断文件是否为空不为空关闭输入流
if (fileInput != null) {
try {
fileInput.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
字节的输出流 FileOutputStream
下面展示一些 内联代码片
。
public static void main(String[] args) {
// 先创建一个文件在指定的磁盘下
// 在E盘下创建一个名为csdn.txt的文本文档的标准文件夹
String path = "E:" + File.separator + "csdn.txt";
File file = new File(path);
FileOutputStream fileOutput = null;
try {
// 判断文件是否创建成功
boolean createNewFile = file.createNewFile();
System.out.println(createNewFile);
fileOutput = new FileOutputStream(file);
// 将字节输出到指定的文件
String str = "你身处年轻,辜负年轻,也快也将不再年轻!";
// 将String型的字符串转换为字节数组
byte[] arr = str.getBytes();
// 利用write()方法实现输出流
fileOutput.write(arr);
// 输出后刷新文件
fileOutput.flush();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
if (fileOutput != null) {
try {
fileOutput.flush();// 刷新文件
fileOutput.close();// 关闭输出流
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}