Io流初学

IO流 (1)

什么是IO流?
把文件以字符,或字节的形式写入电脑内存中

字节流字符流的区别 ?
字符流:一般使用是要对文件进行处理修改 ,主要用于处理文件
字节流:用于拷贝,不修改;
IO流的方法
创建输入流
FileInputStream input = new FileInputStream(str + "lenovo/study/hello.txt");

1. read(); //读取文件
注意 :需要用try/catch包裹
在D盘创建lenovo/study/hello.txt文件;即把一个文件写入电脑内存中
String str = "D:/";
try {
FileInputStream input = new FileInputStream(str + "lenovo/study/hello.txt");
input.read(); // 读取文件
input.close(); // 关闭流
System.out.println();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
创建输出流
FileOutputStream out = new FileOutputStream("D:/lenovo/study/hello.txt");

在上面的基础上在hellow文件中添加一句“hellow world”
即在电脑中显示

2.输出流的方法
写入方法write();
注意: 括号内是要写入字节类型所以需要强制类型转换
try {
FileOutputStream out = new FileOutputStream("D:/lenovo/study/hello.txt");
String b = "hello world";
out.write(b.getBytes()); // 注意括号内是要写入字节类型所以需要强制类型转换
out.close();

} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}


Io流的例题1:
//从一个txt文件写入另一个txt文件
注意:在此处可以复制中文因为不是打印,而是直接复制,于打印有所不同
try {
FileInputStream intput = new FileInputStream("D:/lenovo/study/hello.txt");
FileOutputStream out = new FileOutputStream("D:/lenovo/study/1.txt");
int n = intput.read();
//使用循环吧所有字符复制,文件没读完是是不会等于负一的
while (n != -1) {
out.write(n);
// n=intput.read();

}
intput.close();
out.close();

} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

未完待续更新。。。。。。。

猜你喜欢

转载自blog.csdn.net/qq_38845493/article/details/72633881