I/O流的读写是java SE中的一块重要内容,下面是我总结的几种读写方式,在java7之前流的读写需要手动关闭流,但根据新特性现在只需要将所用到的流放入try的小括号内就可以了;
public class Dome1{
public static void main(String[] args) {
File file1 = Paths.get("D:", "test.txt" ).toFile();
File file2 = Paths.get("D:", "test2.txt").toFile();
try(FileInputStream in = new FileInputStream(file1);
FileOutputStream out = new FileOutputStream(file2)
){
int len = -1;
byte[] buff = new byte[1024];
while((len = in.read(buff))!=-1){
out.write(buff,0,len);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
字符流和字节流的方法一致,不同点在于处理的文件类型不同,以及字节流不涉及缓冲区,字符流则是将数据先存入缓冲区然后再写入文件
public class Dome2 {
public static void main(String[] args) {
File file1 = Paths.get("D:", "test.txt").toFile();
File file2 = Paths.get("D:", "test2.txt").toFile();
try (BufferedReader in = new BufferedReader(new FileReader(file1));
BufferedWriter out = new BufferedWriter(new FileWriter(file2))
) {
//通过缓冲的方式进行高效读写
String len = null;
while((len = in.readLine())!=null){
out.write(len);
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
字符流和字节流之间可以进行转换,在转换时可以选择编码格式
class Dome3{
public static void main(String[] args) {
File file1 = Paths.get("D:", "test.txt").toFile();
Charset charset = Charset.forName("UTF-8");
try (FileInputStream in = new FileInputStream(file1);
InputStreamReader toReader = new InputStreamReader(in,charset);
BufferedReader reader = new BufferedReader(toReader)
){
String len = null;
while ((len=reader.readLine())!=null){
System.out.println(len);
}
} catch (IOException e) {
e.printStackTrace();
}
}
}