Java学习随笔4:Java的IO操作
1. IO流的作用是读写设备上的数据,如硬盘文件、内存、键盘、网络等。根据数据走向,可分为:输入流和输出流;根据处理的数据类型,可分为:字节流和字符流。字节流可以处理所有类型的数据,如MP3、图片、视频等。在读取时,读到一个字节就返回一个字节。在Java中都是以“Stream”结尾的;字符流仅能够处理纯文本数据,如txt文本等。在读取时,读到一个或者多个字节,先查找指定的编码表,然后将查到的字符返回。在Java中对应的类都是以“Reader”或“Writer”结尾。
2. 字符、字节与编码
说明 | 举例 | |
字符 | 人们使用的记号,抽象意义上的一个符号 | '1','中','a',’$‘ |
字节 | 计算机中存储数据的单元,一个8位的二进制数,是一个很具体的存储空间 | 0x01,0x45,0xFA |
ANSI编码 | 系统预设的标准文字存储格式,不是具体的某一种编码,不同的国家和地区使用不同的标准。ANSI编码的一个字符可能使用一个字节或多个字节来表示 |
"中文123" (占7字节) |
UNICODE编码 | 为了是国际间信息交流更加方便,国际组织制定了UNICODE字符集,为各种语言中的每一个字符设定了统一并且唯一的数字编号,以满足跨语言、跨平台进行文本转换,、处理的要求 |
L“中文123” (占10字节) |
3. 使用字节流读取文本数据
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException; public class ReadByteStream {
public static void main(String[] args) {
try {
FileInputStream fis = new FileInputStream("text.txt");
byte[] input = new byte[30];
fis.read(input); String inputString = new String(input,"GBK");
System.out.println(inputString);
// 关闭输入流
fis.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} }
}
4. 使用字节流写入数据
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException; public class ReadByteStream {
public static void main(String[] args) {
try {
FileInputStream fis = new FileInputStream("text.txt");
byte[] input = new byte[30];
fis.read(input); String inputString = new String(input,"GBK");
System.out.println(inputString); // 关闭输入流
fis.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} }
}
5. 文件的的拷贝
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException; public class CopyByByteStream {
public static void main(String[] args) {
try {
FileInputStream fis = new FileInputStream("破碎的瞬间.jpg");
FileOutputStream fos = new FileOutputStream("new.jpg"); byte[] input = new byte[50];
while(fis.read(input) != -1){
fos.write(input);
} fos.close();
fis.close(); System.out.println("done"); } catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
6. 使用缓冲流读写大文件,其读写的速度比普通的字节流快的多
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException; public class ReadByBufferedByteStream {
public static void main(String[] args) {
try {
FileInputStream fis = new FileInputStream("破碎的瞬间.jpg");
BufferedInputStream bis = new BufferedInputStream(fis); // 合理的设置缓冲区的大小,可以对读写效率进行优化 FileOutputStream fos = new FileOutputStream("new1.jpg");
BufferedOutputStream bos = new BufferedOutputStream(fos); // 合理的设置缓冲区的大小,可以对读写效率进行优化
// 字节数组的大小设置原则:大型文件对应的数组可以大一些,小文件对应的数组大小可以小一些
byte[] input = new byte[100];
int count = 0;
long startTime = System.currentTimeMillis();
while(bis.read(input) != -1){
bos.write(input);
count++; //计算读取次数
} bos.close();
fos.close(); bis.close();
fis.close(); long endTime = System.currentTimeMillis();
System.out.println(endTime-startTime);
System.out.println("读取了"+count+"次");
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
7. 使用字符流读写文件
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException; public class ReadWriteByCharStream {
public static void main(String[] args) {
try {
File file = new File("test.txt");
FileInputStream fis = new FileInputStream(file);
FileOutputStream fos = new FileOutputStream("test1.txt"); // 编码设置一致
InputStreamReader isr = new InputStreamReader(fis, "GBK");
OutputStreamWriter osw = new OutputStreamWriter(fos,"GBK"); char input[] = new char[100];
// 加入length防止读取多余数据
int length = 0;
while((length = isr.read(input)) != -1){
String inputString = new String(input,0,length);
osw.write(inputString);
} osw.close();
isr.close();
fos.close();
fis.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
8. 使用带有缓冲的字符流可以读取或写入文件的一行数据,且可以提高读写的效率
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException; public class ReadWriteBufferedCharStream {
public static void main(String[] args) {
try {
File file = new File("test.txt");
FileInputStream fis = new FileInputStream(file);
FileOutputStream fos = new FileOutputStream("test2_buffered.txt"); // 编码设置一致
InputStreamReader isr = new InputStreamReader(fis, "GBK");
OutputStreamWriter osw = new OutputStreamWriter(fos,"GBK"); // 创建带有buffer的字符流
BufferedReader br = new BufferedReader(isr);
// BufferedWriter bw = new BufferedWriter(osw);
PrintWriter pw = new PrintWriter(osw,true);// 自动flush String input = null;
while((input = br.readLine()) != null){
//bw.write(input); // 不包含换行符
pw.println(input);
}
br.close();
// 将缓冲区的内容强制输出,避免遗漏
//bw.flush()bw.close();
pw.close(); osw.close();
isr.close();
fos.close();
fis.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
9. FileReader和FileWriter,处理文本文件
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException; public class TestFileReadWrite {
public static void main(String[] args) {
try {
// 读取文本文件
FileReader fr = new FileReader("test.txt");
BufferedReader br = new BufferedReader(fr); FileWriter fw = new FileWriter("test_new.txt");
BufferedWriter bw = new BufferedWriter(fw); String line;
while((line = br.readLine()) != null){
bw.write(line+"\n");
}
// 所有带有缓冲的流都需要强制输出
bw.flush();
bw.close();
fw.close();
br.close();
fr.close(); } catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} }
}
10. RandomAccessFile随机文件读写
使用多线程在一个文件指定的块位置写入数据。
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.RandomAccessFile; public class MultiWriteFile {
public static void main(String[] args) {
File file = new File("test.txt");
if(file.exists()){
file.delete();
} // 调用多个线程分区写入文件,且如果写入的数据的长度小于块的长度,则块间的空白处仍保留,最后一个块除外
new WriteFile(file, 2).start();
new WriteFile(file, 1).start();
new WriteFile(file, 5).start();
new WriteFile(file, 4).start();
new WriteFile(file, 3).start(); // 读取文件
try {
RandomAccessFile raf = new RandomAccessFile(file, "r");
raf.seek(400); //读取400位置的数据
byte[] output = new byte[20];
raf.read(output);
String str = new String(output);
System.out.println(str); } catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.RandomAccessFile; public class WriteFile extends Thread{
File file;
int block; // 块号
int lenByte = 100; //块的字节大小
public WriteFile(File f,int b){
file = f;
block = b;
} public void run(){
try {
RandomAccessFile raf = new RandomAccessFile(file, "rw");
raf.seek((block-1)*lenByte); //定位到文件的位置
raf.writeBytes("I am ws"+block); //在相应的位置写入数据
for(int i = 0; i < 20; i++){
raf.writeBytes("-");
}
raf.writeBytes("\n");
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
11. Apache IO库commons.io的功能十分强大,可参考common.io的使用。
Java学习随笔4:Java的IO操作的更多相关文章
- Java基础复习笔记系列 七 IO操作
Java基础复习笔记系列之 IO操作 我们说的出入,都是站在程序的角度来说的.FileInputStream是读入数据.?????? 1.流是什么东西? 这章的理解的关键是:形象思维.一个管道插入了一 ...
- Java学习随笔——RMI
RMI(Remote Method Invocation)远程方法注入,用来实现远程方法调用,是实现分布式技术的一种方法.RMI提供了客户辅助对象和服务辅助对象,为客户辅助对象创建了和服务对象相同的方 ...
- java安全编码指南之:文件IO操作
目录 简介 创建文件的时候指定合适的权限 注意检查文件操作的返回值 删除使用过后的临时文件 释放不再被使用的资源 注意Buffer的安全性 注意 Process 的标准输入输出 InputStream ...
- (。・・)ノ~个人java学习随笔记录
基本认识 1.编程思维 根据这几天的java学习,编写程序最重要的就是要有一个清晰的思路.语法上的错误可以跟随着不断的联系与学习来弥补,清晰的思维却只有自己来前期模仿,后面慢慢摸索形成一套属于自己的思 ...
- 【java学习笔记】文件读写(IO流)
1.字节流 FileInputStream.FileOutputStream ①FileInputStream import java.io.FileInputStream; public class ...
- 6.6(java学习笔记)文件分割(IO综合例子)
基本思路: 文件分割:将一个文件分割成若干个独立的文件. 设置分割后小文件文件的字节数,然后读取被分割文件, 将对应的字节数写入分割后的小文件中. 使用seek定位下一次读取位置. 文件 ...
- Java学习随笔---常用API(二)
Object类的toString方法 将一个对象返回为字符串形式,但一般使用的时候会覆盖重写toString方法 Object类是所有类的父亲 // public class Person { pri ...
- Java学习之路 -- Java怎么学?
@ 目录 java基础怎么学? 学完基础学什么? 几个常用框架学完学什么? MQ JVM的知识跑不掉 微服务等等 其他 数据结构和算法 java基础怎么学? 当时,作为懵懂的小白,大一学习了c和c++ ...
- Java学习(JDBC java连接数据库)
一.概述 JDBC(Java Data Base Connectivity,java数据库连接)是一种用于执行SQL语句的Java API,可以为多种关系数据库提供统一访问,它由一组用Java语言编写 ...
- Java学习之道:Java 导出EXCEL
1.Apache POI简单介绍 Apache POI是Apache软件基金会的开放源代码函式库.POI提供API给Java程式对Microsoft Office格式档案读和写的功能. .NET的开 ...
随机推荐
- Unity3D研究院之拓展系统自带组件的Inspector视图
转自 http://www.xuanyusong.com/archives/3455 using UnityEngine; using System.Collections; using UnityE ...
- js中修改标签的hidden属性
hidden属性在html5中,只要存在,就是隐藏效果,而不论值为多少 要显示元素,要删除hidden属性,而不是设置为false <script type="text/javascr ...
- [Linux]非外网环境下配置lnmp心得
1.安装gcc编译器 基本所有编译安装包都需要gcc编译器,而且编译安装gcc也需要一个编译器,这是一个悖论.所以,这里只能寻求rpm包安装.但是rpm包需要匹配特定的操作系统内核,所以没有一个通用的 ...
- oracle定时器,调用存储过程,定时从n张表中取值新增到本地一张表中
--创建新增本地数据库的存储过程create or replaceprocedure pro_electric_record as begin insert into electric_met ...
- SQL Server output经典使用
output经典使用 分类: sql2012-02-16 18:17 409人阅读 评论(0) 收藏 举报 outputinserttabledeletegonull OUTPUT是SQL SERVE ...
- Linear regression with one variable算法实例讲解(绘制图像,cost_Function ,Gradient Desent, 拟合曲线, 轮廓图绘制)_矩阵操作
%测试数据 'ex1data1.txt', 第一列为 population of City in 10,000s, 第二列为 Profit in $10,000s 1 6.1101,17.592 5. ...
- hdu 2159 FATE
题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=2159 思路:二维完全背包,状态转移方程为: f[j][l]=max(f[j][l],f[j-b[i]] ...
- Xcode 7如何免费真机调试iOS应用
Xcode 7如何免费真机调试iOS应用的简单方式: 运行Xcode后,点击菜单中的Preferences…进入Accounts标签,这里选择添加Apple ID:在弹出的对话框中登入你的Apple ...
- ViewPager部分源码分析三:scroll
手指在屏幕上滑动,触发到onTouchEvent(),执行case MotionEvent.ACTION_MOVE: ... public boolean onTouchEvent(MotionEve ...
- MVC缓存01,使用控制器缓存或数据层缓存
对一些浏览频次多.数据量大的数据,使用缓存会比较好,而对一些浏览频次低,或内容因用户不同的,不太适合使用缓存. 在控制器层面,MVC为我们提供了OutputCacheAttribute特性:在数据 ...