一、字节流: FileOutputStream 和 FileInputStream
1、FileInputStream
普通的写法
public class TestDemo {
public static void main(String[] args) {
//IO流分为字节流,字符流
// ileInputStream 属于字节流,每次只能处理一个字节,即一个byte,通常处理图片,音频,视频的文件,也可以处理文本文件,但是通常用于处理上述文件,处理完成后一定要.close()
FileInputStream inputStream = null;
try {
inputStream = new FileInputStream("./aaa.txt");
byte[] buf = new byte[128];
int n = 0;
while ( (n = inputStream.read(buf)) != -1) {
String str = new String(buf, 0, n);
System.out.println("str = " + str);
}
} catch (FileNotFoundException e) {
log.info("xxx文件找不见");
e.printStackTrace();
} catch (IOException e) {
log.info("xxx");
e.printStackTrace();
}finally {
try {
if (inputStream != null) {
inputStream.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
try-catch-resource写法
/**
* 这种写法是try-catch-resource,不需要我们写.close()方法,这是java1.7后新增的方法。
* java会自动帮我们来关闭,但是我们需要把关闭的流的声明及初始化需要写在try后面你的()里面
* 并不是所有的流都是可以这样关闭,只有实现了Closeable接口的可以这样关闭
*/
public class TestDemo {
public static void main(String[] args) {
try(FileInputStream inputStream = new FileInputStream("./aaa.txt");) {
byte[] buf = new byte[128];
int n = 0;
while ( (n = inputStream.read(buf)) != -1) {
String str = new String(buf, 0, n);
System.out.println("str = " + str);
}
} catch (FileNotFoundException e) {
log.info("xxx文件找不见");
e.printStackTrace();
} catch (IOException e) {
log.info("xxx");
e.printStackTrace();
}
}
}
2、FileOutputStream
/**
* 输出流默认的是会覆盖之前输出的东西,不需要覆盖的话需要加一个参数,如下代码中的true
*/
public class TestDemo {
public static void main(String[] args) {
try(FileOutputStream outputStream = new FileOutputStream("./aaa.txt",true);) {
outputStream.write("hello".getBytes());
} catch (FileNotFoundException e) {
log.info("xxx文件找不见");
e.printStackTrace();
} catch (IOException e) {
log.info("xxx");
e.printStackTrace();
}
}
}
二、字符流
/**
* 输出流默认的是会覆盖之前输出的东西,不需要覆盖的话需要加一个参数,如下代码中的true
* 字符流通常用来处理文本
*/
public class TestDemo {
public static void main(String[] args) throws IOException {
FileWriter out = new FileWriter("./aaa.txt",true);
out.write("\n你好".toCharArray());
out.close();
FileReader in = new FileReader("./aaa.txt");
int n = 0;
char[] chars = new char[128];
while ((n = in.read(chars)) != -1) {
System.out.println(new String(chars,0,n));
}
in.close();
}
}
三、高级字符流
public static void main(String[] args) throws Exception {
PrintWriter out = new PrintWriter(
new OutputStreamWriter(
new BufferedOutputStream(
new FileOutputStream("./bbb.txt",true))
)
);
out.println("shishishi");
out.flush();
out.close();
// 可以实现字节流向字符流的转换,这是需要注意字符编码的问题,如下面代码中的 utf-8
BufferedReader reader = new BufferedReader(
new InputStreamReader(
new BufferedInputStream( // 缓冲流,代码中经常这样写
new FileInputStream("./bbb.txt")),"UTF-8")
);
String str = null;
while ((str = reader.readLine()) != null) {
System.out.println("str = " + str);
}
reader.close();
}