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. mysql性能优化学习笔记-存储引擎

    mysql体系架构 客户端(java.php.python等) mysql服务层(连接管理器.查询解析器.查询优化器.查询缓存) mysql存储引擎(innodb.myisam等) 存储引擎针对表而言 ...

  2. C++复制控制

    1.复制构造函数可用于: (1)根据另一个同类型的对象显示或隐式初始化一个对象 string str1="test";   //隐式 string str2=str1; //显示 ...

  3. 8. javacript高级程序设计-BOM

    1. BOM 1.1 window BOM的核心对象是window,它表示浏览器的一个实例.在浏览器中,window对象有双重身份, 1.1.1 全局作用域 由于window对象同时扮演着ECMASc ...

  4. nyoj_299_Matrix Power Series_矩阵快速幂

    Matrix Power Series 时间限制:1000 ms  |  内存限制:65535 KB 难度:4   描述 Given a n × n matrix A and a positive i ...

  5. OKhttp的封装(下)

    OKhttpManager2.Class  请求工具类 package com.example.administrator.okhttp3; import android.os.Handler; im ...

  6. 【leetcode】Insertion Sort List (middle)

    Sort a linked list using insertion sort. 思路: 用插入排序对链表排序.插入排序是指每次在一个排好序的链表中插入一个新的值. 注意:把排好序的部分和未排序的部分 ...

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

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

  8. 本地Yum

    1. mkdir xxx #新建文件夹 (新建一个挂载需要的文件夹) 2.配置本地yum源(挂载光盘) 3.进入 yum.repos.d 4.ls (查看当前文件夹全部的文件) 并 mv 修改   除 ...

  9. java jsp调用shell(带参数)脚本并返回值

    test.jsp <%@ page language="java" import="java.util.List,java.util.ArrayList,java. ...

  10. 129. Sum Root to Leaf Numbers

    题目: Given a binary tree containing digits from 0-9 only, each root-to-leaf path could represent a nu ...