IO流基础(一)
目标
- 掌握文件的写操作
- 掌握文件的读操作
- 掌握文件的读写
一、字节输出流
1.1 实现向txt文件种写入一段话
public class IO1 {
public static void main(String[] args) throws IOException {
// 1.创建字节输出流对象:调用系统功能创建文件,创建字节输出流对象,让字节输出流对象指向文件
// 2.调用对象方法写数据:写的参数给int类型或者字节数组。(具体可以看api文档)
// 3.关闭释放资源
FileOutputStream fos = new FileOutputStream("fos.txt");
/*底层知识:该构造器会自动new 一个File对象
public FileOutputStream(String name) throws FileNotFoundException {
this(name != null ? new File(name) : null, false);
}
*/
String a = "霜雪千年";
fos.write(a.getBytes(StandardCharsets.UTF_8));
fos.close();
}
}
1.2 实现文件写入的换行和追加
public class IO3 {
public static void main(String[] args) throws IOException {
/*
各操作系统换行符
windows:\r\n
linux:\n
mac:\r
FileOutputStream构造器的第二个参数默认为false,即从头开始写;true表示追加的意思
*/
FileOutputStream fos = new FileOutputStream("fos.txt",true);
String a = "霜雪千年\r\n";
fos.write(a.getBytes(StandardCharsets.UTF_8));
fos.close();
}
}
1.3 文件写入+异常处理
public class IO4 {
public static void main(String[] args){
FileOutputStream fos = null;
try{
fos = new FileOutputStream("P://fos.txt");
String str = "异常处理测试";
fos.write(str.getBytes(StandardCharsets.UTF_8));
}
catch (Exception e){
e.printStackTrace();
}
finally {
if (fos!=null)
try {
System.out.println("文件存在,释放资源");
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
二、字节输入流
2.1 单个字节读取
public class IO1 {
public static void main(String[] args) throws IOException {
//字节流读数据一次读一个字节
//因为英文是一个字节对应一个字母,所以这样读是没问题的
//但是中文按照utf8的编码,三个字节对应一个中文字符,所以不能用下面的方法
FileInputStream fis = new FileInputStream("fos.txt");
int content;
while ((content = fis.read()) != -1){
System.out.print((char) content);
}
fis.close();
}
}
2.2 字节数组读取(可以读取中文)
public class IO2 {
public static void main(String[] args) throws IOException {
//读取一段中文字符
FileInputStream fis = new FileInputStream("fos.txt");
byte[] bt = new byte[1024];
int len;
while ((len = fis.read(bt))!=-1){
//这里有个坑:要注意len表示本次读取的实际长度,如果写死,可能会把上次的内容也打印出来了;
System.out.print(new String(bt, 0, len));
}
}
}
2.3 实现图片文件的拷贝
public class imageCopy {
public static void main(String[] args) throws IOException {
// 用idea写java路径需要注意一下,如果不清楚项目运行的当前路径,可以用File类里的方法测试一下
// System.out.println(new File("./").getAbsolutePath());
CopyImage("src\\javaBasics\\IO\\BIO\\InputStreamTest\\a.png", "src\\javaBasics\\IO\\BIO\\InputStreamTest\\b.png");
}
public static void CopyImage(String path1, String path2) throws IOException {
FileInputStream fis = new FileInputStream(path1);
FileOutputStream fos = new FileOutputStream(path2);
byte[] bt = new byte[1024];
int len;
while ((len = fis.read(bt)) != -1){
fos.write(bt,0,len);
}
fis.close();
fos.close();
System.out.println("copy成功");
}
}
三、小结
-
如何区分输入流和输出流?
答:可以把字节想象成一个人,他输入就是读博客,他输出就是写博客
-
如何确定字符流和字节流的使用场景
答:记事本可以打开的可以用字符流,不能打开就用字节流,字符流能用的字节流都可以用!
-
对项目文件路径不清楚可以用File类里的方法。