Java语法回顾之InputSteam&&OutputSteam
读了那么多年的书让我明白一个道理。人要稳重,不要想到啥就做啥。做一行越久即使你不会,几年之后慢慢的你也会了,加上一点努力你或许你能成为别人眼中的专家。
通过字节流往文件中写数据
/*
* 通过字节流往文件中写数据。
*
* 字节输出流操作步骤:
* A:创建字节输出流对象
* B:调用写数据的方法
* C:释放资源
*/
通过字节流往文件中写数据代码测试
public class FileOutputStreamDemo {
public static void main(String[] args) throws IOException {
// 创建字节输出流对象(true为追加写入)
// FileOutputStream fos = new FileOutputStream("a.txt",true);
FileOutputStream fos = new FileOutputStream("a.txt");
// 调用写数据的方法
// 写入一个字节
// fos.write(97);
// fos.write(98);
// fos.write(99);
// fos.flush();
// 写一个字节数组
// byte[] bys = { 97, 98, 99, 100, 101 };
byte[] bys = "abcde".getBytes();
// fos.write(bys);
// 写一个字节数组的一部分
fos.write(bys, 0, 2);
// 释放资源
fos.close();
}
}
字节输入流操作步骤
/*
* 字节输入流操作步骤:
* A:创建字节输入流对象
* B:调用读取数据的方式,并显示
* C:释放资源
*/
字节输入流操作步骤代码测试
public class FileInputStreamDemo {
public static void main(String[] args) throws IOException {
// 创建字节输入流对象
FileInputStream fis = new FileInputStream("b.txt");
// 调用读取数据的方式,并显示
// 方式1
// int by = 0;
// while ((by = fis.read()) != -1) {
// System.out.println(by);
// }
// 方式2
byte[] bys = new byte[1024];
int len = 0;
while ((len = fis.read(bys)) != -1) {
System.out.print(new String(bys, 0, len));
}
// 释放资源
fis.close();
}
}