io 基本操作
来源:互联网 发布:php socket 客服系统 编辑:程序博客网 时间:2024/06/12 14:52
1 Io
可以分为 字节流 字符流
例子 字节流
读一个写一个
//得到文件
File file = new File("D:/test.txt");
try {
//把文件交个输入流
FileInputStream in = new FileInputStream(file);
//需要输出的
FileOutputStream out = new FileOutputStream("D:/ttd.txt");
int b =0;
while((b=in.read())!=-1){
out.write(b);
}
out.flush();
in.close();
out.close();
} catch (FileNotFoundException e) {
System.out.println("找不到文件");
} catch (IOException e) {
System.out.println("读取文件失败");
}
}
2 先把数据读出来在写入
//得到文件
File file = new File("D:/test.txt");
try {
//拿到文件给输入流
FileInputStream in = new FileInputStream(file);
byte[]ter = new byte[1024];
//将文件读到数组中
//in.read(ter);
FileOutputStream out = new FileOutputStream("D:/tt.txt");
//判断是否为空
if(in.read(ter)!=-1) {
//将数组的数据写进去txt 文件中
out.write(ter);
}
out.flush();
in.close();
out.close();
} catch (FileNotFoundException e) {
System.out.println("找不到文件");
} catch (IOException e) {
System.out.println("文件读入失败");
}
}
字符流
//字符流
File file = new File("D:/test.txt");
try {
FileReader re = new FileReader(file);
//读取一个字符 返回 int
//如果为-1 结尾
//re.read();
int b =0;
FileWriter w = new FileWriter("D:/wr.txt");
while((b= re.read())!=-1){
w.write(b);
}
w.flush();
re.close();
w.close();
} catch (FileNotFoundException e) {
System.out.println("文件找不到");
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
System.out.println("文件读入失败");
}
}
2 //字符流 存储到数组里
File file = new File("D:/test.txt");
try {
FileReader re = new FileReader(file);
FileWriter wr = new FileWriter("D:/t3.txt");
//定义数组并保存文件到数组中
char[]c = new char[1024];
int b =re.read(c);
if(b!=-1){
wr.write(c);
}
wr.flush();
re.close();
wr.close();
} catch (FileNotFoundException e) {
System.out.println("找不到");
e.printStackTrace();
} catch (IOException e) {
System.out.println("错误");
e.printStackTrace();
}
}
4 . 缓存流
//缓存流
File file = new File("D:/test.txt");
InputStream in;
try {
in = new FileInputStream(file);
BufferedInputStream bf = new BufferedInputStream(in,1024);
byte[]by = new byte[1024];
OutputStream out = new FileOutputStream("D:/t4.txt");
BufferedOutputStream bfo = new BufferedOutputStream(out);
if(bf.read(by)!=-1){
bfo.write(by);
}
bfo.flush();
bf.close();
bfo.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
缓存流的使用理解
先把一定大小的数据保存到一个小桶里面 read()的时候会在里面拿到 !减少了i/o ,否则去读取新的数据到缓冲区(通常比请求的数据要多),
- IO的基本操作
- linux 基本io操作
- IO基本操作
- Io基本操作
- 基本的IO操作
- java基本IO操作
- io 基本操作
- 基本IO操作(一)
- common-io基本操作
- 基本IO操作 、 文本数据IO操作
- java笔记-IO流-IO基本操作
- java 基本的io操作
- Java IO 一些基本操作
- Java 基本的IO操作
- 025 Java 基本IO操作
- Java基础--IO基本操作
- 黑马程序员--基本IO操作
- Java IO流基本操作
- 常用的java代码
- Spring常用注解
- gradle 构建 hello world
- Ganglia配置安装
- memmove函数实现
- io 基本操作
- Java 快讯功能开发记录
- Android —— 十分酷炫的界面效果集合
- butterknife查找viewid 出错
- Android7.0 多窗口你值得拥有
- 远程脚本概述
- python socket编程详细介绍
- jQuery 核心 - jQuery() 方法
- Mirantis OpenStack 6.0 base on CentOS 6.5 Install Doc