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操作的更多相关文章

  1. Java基础复习笔记系列 七 IO操作

    Java基础复习笔记系列之 IO操作 我们说的出入,都是站在程序的角度来说的.FileInputStream是读入数据.?????? 1.流是什么东西? 这章的理解的关键是:形象思维.一个管道插入了一 ...

  2. Java学习随笔——RMI

    RMI(Remote Method Invocation)远程方法注入,用来实现远程方法调用,是实现分布式技术的一种方法.RMI提供了客户辅助对象和服务辅助对象,为客户辅助对象创建了和服务对象相同的方 ...

  3. java安全编码指南之:文件IO操作

    目录 简介 创建文件的时候指定合适的权限 注意检查文件操作的返回值 删除使用过后的临时文件 释放不再被使用的资源 注意Buffer的安全性 注意 Process 的标准输入输出 InputStream ...

  4. (。・・)ノ~个人java学习随笔记录

    基本认识 1.编程思维 根据这几天的java学习,编写程序最重要的就是要有一个清晰的思路.语法上的错误可以跟随着不断的联系与学习来弥补,清晰的思维却只有自己来前期模仿,后面慢慢摸索形成一套属于自己的思 ...

  5. 【java学习笔记】文件读写(IO流)

    1.字节流 FileInputStream.FileOutputStream ①FileInputStream import java.io.FileInputStream; public class ...

  6. 6.6(java学习笔记)文件分割(IO综合例子)

    基本思路: 文件分割:将一个文件分割成若干个独立的文件.    设置分割后小文件文件的字节数,然后读取被分割文件, 将对应的字节数写入分割后的小文件中.     使用seek定位下一次读取位置. 文件 ...

  7. Java学习随笔---常用API(二)

    Object类的toString方法 将一个对象返回为字符串形式,但一般使用的时候会覆盖重写toString方法 Object类是所有类的父亲 // public class Person { pri ...

  8. Java学习之路 -- Java怎么学?

    @ 目录 java基础怎么学? 学完基础学什么? 几个常用框架学完学什么? MQ JVM的知识跑不掉 微服务等等 其他 数据结构和算法 java基础怎么学? 当时,作为懵懂的小白,大一学习了c和c++ ...

  9. Java学习(JDBC java连接数据库)

    一.概述 JDBC(Java Data Base Connectivity,java数据库连接)是一种用于执行SQL语句的Java API,可以为多种关系数据库提供统一访问,它由一组用Java语言编写 ...

  10. Java学习之道:Java 导出EXCEL

    1.Apache POI简单介绍  Apache POI是Apache软件基金会的开放源代码函式库.POI提供API给Java程式对Microsoft Office格式档案读和写的功能. .NET的开 ...

随机推荐

  1. Context.managedQuery()和context.getContentResolver()获取Cursor关闭注意事项

    在获取图片缩略图时,获取游标并进行相关的操作. Cursor cursor = context.getContentResolver().query(MediaStore.Images.Thumbna ...

  2. Storm集群的安装配置

    Storm集群的安装分为以下几步: 1.首先保证Zookeeper集群服务的正常运行以及必要组件的正确安装 2.释放压缩包 3.修改storm.yaml添加集群配置信息 4.使用storm脚本启动相应 ...

  3. ACM/ICPC 之 DFS求解欧拉回路+打表(POJ1392)

    本题可以通过全部n位二进制数作点,而后可按照某点A的末位数与某点B的首位数相等来建立A->B有向边,以此构图,改有向图则是一个有向欧拉回路,以下我利用DFS暴力求解该欧拉回路得到的字典序最小的路 ...

  4. Java for LeetCode 205 Isomorphic Strings

    Given two strings s and t, determine if they are isomorphic. Two strings are isomorphic if the chara ...

  5. Django~Settings.py

    配置 数据库 默认sqlite, 支持Mysql,postgresql,oracle 更改时区 查看表结构 .schema (SQLite), display the tables Django cr ...

  6. Mathematics:Find a multiple(POJ 2356)

    找组合 题目大意:给你N个自然数,请你求出若干个数的组合的和为N的整数倍的数 经典鸽巢原理题目,鸽巢原理的意思是,有N个物品,放在N-1个集合中,则一定存在一个集合有2个元素或以上. 这一题是说有找出 ...

  7. Mathematics:Prime Path(POJ 3126)

    素数通道 题目大意:给定两个素数a,b,要你找到一种变换,使得每次变换都是素数,如果能从a变换到b,则输出最小步数,否则输出Impossible 水题,因为要求最小步数,所以我们只需要找到到每个素数的 ...

  8. 【linux】linux下运行java程序

    参考了http://www.cnblogs.com/howard-queen/archive/2012/01/30/2331795.html 第一步:用vim先写一个java程序  first.jav ...

  9. IOS - 唯一标识符的获得和更新

    苹果公司不可能让其他人获得个人终端的唯一标识符,所以一个终端给另一个终端发送消息,必须经过苹果的APNS(Apple Push Notification Service)....而且苹果为了防止苹果用 ...

  10. 解决Idea创建maven-archetype-webapp项目无java目录的问题

    一.背景 在适用IDEA创建maven-archetype-webapp项目的时候,创建完成后发现在main文件夹下没有java源文件夹,不少小伙伴也遇到该问题,但不知道怎么解决,下面我就来分享解决步 ...