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. (转)C++0x语言新特性一览

    转自:http://blog.csdn.net/zwvista/article/details/2429781 原文请见http://en.wikipedia.org/wiki/C%2B%2B0x. ...

  2. redis 中文字符显示

    2015年5月20日 09:57:01 星期三 方法一: redis-cli -h --raw 方法二: linux 终端: echo -e "\xe7\xa5\x9e\xe6\xa3\x8 ...

  3. ACM/ICPC 之 差分约束系统两道(ZOJ2770-POJ1201)

    当对问题建立数学模型后,发现其是一个差分方程组,那么问题可以转换为最短路问题,一下分别选用Bellmanford-SPFA解题 ZOJ2770-Burn the Linked Camp //差分约束方 ...

  4. Kinect SDK 安装失败

    错误提示:Kinect Management failed to start. 原因: 1, Kinect Management 服务相依的 Plug and Play的服务没有启动. 2,系统安装了 ...

  5. SAP打印出库单 新需求

    *&---------------------------------------------------------------------* *& Report  Z_SD_CKD ...

  6. BestCoder27 1002.Taking Bus(hdu 5163) 解题报告

    题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=5163 题目意思:有 n 个车站,给出相邻两个车站的距离,即车站 i 和车站 i+1 的距离为 di ( ...

  7. Android 运行时权限处理

    引言 Android 6.0 (API 23) 开始引入了运行时权限检查 (Permissions at Run Time),用户不需要在安装时同意授予应用权限,而是在应用运行时动态去申请所需要的权限 ...

  8. 【leetcode】Remove Linked List Elements(easy)

    Remove all elements from a linked list of integers that have value val. ExampleGiven: 1 --> 2 --& ...

  9. VS中新建类

    通常我们在VS中添加类,比如要声明一个car的类 我们通常在新建的时候会写成CCar,虽然新建出来的文件的名词是car,但是我们使用这个类来声明一个类的时候, 是CCar car; 如果新建类写成Ca ...

  10. 解决VS2010 C++ DLL不能断点调试的问题

    问题产生的过程是这样的,向exe项目(CSharp)中添加dll工程(c++开发)的引用,并将引用工程的属性“Link Library Dependencies”的值设为true,这样,在不加入lib ...