类别 | 基类 | 常用类 |
字节流的读写 | InputStream和OutputStream | BufferInputStream、BufferOutputStream FileInputStream、 FileOutputStream |
字符流的读写 | Reader和Writer | BUfferReader BufferWriter |
转换流 | InputStreamReader :字节转换成字符的一个输入流,最后,以字符方式读取数据。 OutputStreamWriter :字符转换成字节的一个输出流,最后,以字节方式输出数据。 |
File[] files = new File(".").listFiles(new FilenameFilter() {
@Override
public boolean accept(File dir, String name) {
return dir.isHidden();
}
});
//简写后形式如下
File[] files1 = new File(".").listFiles(File::isHidden);
//File的重要方法
File file = new File("src/main/resources/ss.txt");
file.mkdir();//父路径必须存在否则报错
file.mkdirs();//父路径不存在则创建
file.exists();//判断是文件否存在
字节的输入输出实例,记住要关闭流,这里用了java7以后语法不用显示的关闭流的方式
//放入try语句中之后会自动关闭流
try( FileInputStream fileInputStream =new FileInputStream(new File("src/main/resources/data.csv"));
FileOutputStream fileOutputStream = new FileOutputStream(new File("src/main/resources/data1.csv"))) {
int len=0;
byte[] chars =new byte[1024];//一次读1024字节,写1024字节
while((len=fileInputStream.read(chars))!=-1){
System.out.println(new String(chars,0,len));
fileOutputStream.write(chars,0,len);
}
}catch (Exception E){
E.printStackTrace();
}
//带缓冲的字节输入输出流,能提高效率,用的是包装设计模式,FileOutputStream的第二个参数为true时将会在之前文件中添加而不是覆盖
try(BufferedInputStream bufferedInputStream = new BufferedInputStream(new FileInputStream("."));
BufferedOutputStream bufferedOutputStream = new BufferedOutputStream(new FileOutputStream(".",true))){
int len=0;
byte[] chars =new byte[1024];
while((len=bufferedInputStream.read(chars))!=-1){
bufferedOutputStream.write(chars,0,len);
}
}catch (Exception e){
e.printStackTrace();
}
//BufferedReader字符输入缓冲,BufferedWriter字符输出缓冲
try(BufferedReader bufferedReader = new BufferedReader(new FileReader("."));
BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter("."))){
int len=0;
char[] chars =new char[1024];
while((len=bufferedReader.read(chars))!=-1){
// bufferedReader.readLine();BufferedReader特有方法,读一行数据
bufferedWriter.write(chars,0,len);
bufferedWriter.newLine();//BufferedWriter特有方法换行
}
}catch (Exception e){
e.printStackTrace();
}
转换实例
//这里我们也用缓冲字符输出和输入类进行包装,提高转换效率
try (
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(new FileInputStream("src/main/resources/data.csv")));
BufferedWriter bufferedWriter1 = new BufferedWriter(new OutputStreamWriter(new FileOutputStream("src/main/resources/data1.csv", true)));
) {
int len = 0;
while (len != -1) {
char[] arr = new char[1024];
if ((len = bufferedReader.read(arr)) != -1) {
bufferedWriter1.newLine();
bufferedWriter1.write(arr, 0, len);
}
}
} catch (Exception e) {
e.printStackTrace();
}
new InputStreamReader(new FileInputStream(new File("e:/123.doc")),"utf-8");
new OutputStreamWriter(new FileOutputStream(new File("e:/456.doc")),"utf-8");