1、流的分类

  (1)输入流和输出流(划分输入/输出流时是从程序运行所在内存的角度来考虑的)

    输入流:只能从中读取数据,而不能向其写入数据。

    输出流:只能向其写入数据,而不能从中读取数据。

    输入流主要由InputStream和Reader作为基类,输出流主要由OutputStream和Writer作为基类。它们都是抽象基类,无法直接创建实例。

  (2)字节流和字符流

    字节流和字符流的用法几乎完全一样,区别在于字节流和字符流操作的数据单元不同——字节流操作的数据单元是8-bit的字节,而字符流操作的数据单元是16-bit的字符。

    字节流主要由InputStream和OutputStream作为基类,而字符流则主要由Reader和Writer作为基类。

  (3)节点流和处理流

    可以从/向一个特定的IO设备(如磁盘、网络)读/写数据的流,称为节点流,节点流也被称为低级流。

    处理流则用于对一个已经存在的流进行连接或封装,通过封装后的流来实现数据读/写功能。处理流也被称为高级流。

2、InputStream和Reader

  在InputStream里包含你的方法如下:

All Methods Instance Methods Abstract Methods Concrete Methods 
Modifier and Type Method Description
int available​()
Returns an estimate of the number of bytes that can be read (or skipped over) from this input stream without blocking by the next invocation of a method for this input stream.
void close​()
Closes this input stream and releases any system resources associated with the stream.
void mark​(int readlimit)
Marks the current position in this input stream.(在记录指针当前位置记录一个标记(mark))
boolean markSupported​()
Tests if this input stream supports the mark and reset methods.
abstract int read​()
Reads the next byte of data from the input stream.(字节数据可以直接转换为int类型)
int read​(byte[] b)
Reads some number of bytes from the input stream and stores them into the buffer array b.(最多读取b.length个字节的数据,并将其存储在字节数组b中,放入数组b中时,返回实际读取的字节数)
int read​(byte[] b, int off, int len)
Reads up to len bytes of data from the input stream into an array of bytes.(最多读取b.length个字节的数据,并将其存储在字节数组b中,放入数组b中时,并不是从数组起点开始,而是从off位置开始,返回实际读取的字节数)
byte[] readAllBytes​()
Reads all remaining bytes from the input stream.
int readNBytes​(byte[] b, int off, int len)
Reads the requested number of bytes from the input stream into the given byte array.
void reset​()
Repositions this stream to the position at the time the mark method was last called on this input stream.(将此流的记录指针重新定位到上一次记录标记(mark)的位置)
long skip​(long n)
Skips over and discards n bytes of data from this input stream.(记录指针向前移动n个字节/字符)
long transferTo​(OutputStream out)
Reads all bytes from this input stream and writes the bytes to the given output stream in the order that they are read.

  在Reader里包含方法如下:

Constructors 
Modifier Constructor Description
protected Reader​()
Creates a new character-stream reader whose critical sections will synchronize on the reader itself.                                                                                                                                               
protected Reader​(Object lock)
Creates a new character-stream reader whose critical sections will synchronize on the given object.
Modifier and Type Method Description
abstract void close​()
Closes the stream and releases any system resources associated with it.
void mark​(int readAheadLimit)
Marks the present position in the stream.
boolean markSupported​()
Tells whether this stream supports the mark() operation.
int read​()
Reads a single character.
int read​(char[] cbuf)
Reads characters into an array.(最多读取cbuf.length个字符的数据,并将其存储在字符数组cbuf中,返回实际读取的字符数)                                                                         
abstract int read​(char[] cbuf, int off, int len)
Reads characters into a portion of an array.
int read​(CharBuffer target)
Attempts to read characters into the specified character buffer.
boolean ready​()
Tells whether this stream is ready to be read.
void reset​()
Resets the stream.
long skip​(long n)
Skips characters.

  程序直到read(char[] cbuf)或者read(byte[] b)方法返回-1,即表明到了输入流的结束点。

 package com.zyjhandsome.io;

 import java.io.*;

 public class FileInputStreamTest {

     public static void main(String[] args){
// 用于 保存呢实际读取的字节数
int hasRead = 0;
// 创建字节输入流
FileInputStream fis = null;
try {
fis = new FileInputStream("D:\\zhaoyingjun\\eclipse-workspace\\CollectionTest\\src\\com\\zyjhandsome\\io\\FileInputStreamTest.java");
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
System.out.println("找不到指定文件");
System.exit(-1);
} try {
long num = 0;
while ((hasRead = fis.read()) != -1)
{
System.out.print(((char)hasRead));
num++;
}
fis.close();
System.out.println();
System.out.println("共读取了" + num + "个字节");
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
System.out.print("文件读取错误");
System.exit(-1);
}
}
}

  输出内容(因为是按照字节输出,因此对于中文(字符型)会读取时会出现?的现象):

 package com.zyjhandsome.io;

 import java.io.*;

 public class FileInputStreamTest {

     public static void main(String[] args){
// ???? ±???????????????×?????
int hasRead = 0;
// ???¨×????????÷
FileInputStream fis = null;
try {
fis = new FileInputStream("D:\\zhaoyingjun\\eclipse-workspace\\CollectionTest\\src\\com\\zyjhandsome\\io\\FileInputStreamTest.java");
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
System.out.println("?????????¨????");
System.exit(-1);
} try {
long num = 0;
while ((hasRead = fis.read()) != -1)
{
System.out.print(((char)hasRead));
num++;
}
fis.close();
System.out.println();
System.out.println("????????" + num + "??×???");
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
System.out.print("?????????í?ó");
System.exit(-1);
}
}
} 共读取了940个字节
 package com.zyjhandsome.io;

 import java.io.FileInputStream;
import java.io.*; public class FileReaderTest { public static void main(String[] args) {
// TODO Auto-generated method stub
// 用于保存呢实际读取的字节数
int hasRead = 0;
// 创建字节输入流
FileReader fr = null;
try {
fr = new FileReader("D:\\zhaoyingjun\\eclipse-workspace\\CollectionTest\\src\\com\\zyjhandsome\\io\\FileInputStreamTest.java");
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
System.out.println("找不到指定文件");
System.exit(-1);
} try {
long num = 0;
while ((hasRead = fr.read()) != -1)
{
System.out.print(((char)hasRead));
num++;
}
fr.close();
System.out.println();
System.out.println("共读取了" + num + "个字符");
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
System.out.print("文件读取错误");
System.exit(-1);
}
} }

  输出内容:

 package com.zyjhandsome.io;

 import java.io.*;

 public class FileInputStreamTest {

     public static void main(String[] args){
// 用于保存呢实际读取的字节数
int hasRead = 0;
// 创建字节输入流
FileInputStream fis = null;
try {
fis = new FileInputStream("D:\\zhaoyingjun\\eclipse-workspace\\CollectionTest\\src\\com\\zyjhandsome\\io\\FileInputStreamTest.java");
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
System.out.println("找不到指定文件");
System.exit(-1);
} try {
long num = 0;
while ((hasRead = fis.read()) != -1)
{
System.out.print(((char)hasRead));
num++;
}
fis.close();
System.out.println();
System.out.println("共读取了" + num + "个字节");
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
System.out.print("文件读取错误");
System.exit(-1);
}
}
} 共读取了897个字符
 package com.zyjhandsome.io;

 import java.io.*;

 public class FileReaderTester2 {

     public static void main(String[] args) throws IOException{
// TODO Auto-generated method stub
try {
// 创建字节输入流
FileReader fr = new FileReader("D:\\zhaoyingjun\\eclipse-workspace\\CollectionTest\\src\\com\\zyjhandsome\\io\\FileInputStreamTest.java");
// 创建一个 长度为32的“竹筒”
char[] cbuf = new char[32];
// 用于保存呢实际读取的字节数
int hasRead = 0;
// 使用循环来重复读取字符数
while ((hasRead = fr.read(cbuf)) > 0)
{
// 取出“竹筒”中的水滴(字符),将字符数组转换成字符串输入
System.out.print(new String(cbuf, 0, hasRead));
}
fr.close();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
System.out.println("找不到指定文件");
System.exit(-1);
}
}
}

  输出结果:

 package com.zyjhandsome.io;

 import java.io.*;

 public class FileInputStreamTest {

     public static void main(String[] args){
// 用于保存呢实际读取的字节数
int hasRead = 0;
// 创建字节输入流
FileInputStream fis = null;
try {
fis = new FileInputStream("D:\\zhaoyingjun\\eclipse-workspace\\CollectionTest\\src\\com\\zyjhandsome\\io\\FileInputStreamTest.java");
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
System.out.println("找不到指定文件");
System.exit(-1);
} try {
long num = 0;
while ((hasRead = fis.read()) != -1)
{
System.out.print(((char)hasRead));
num++;
}
fis.close();
System.out.println();
System.out.println("共读取了" + num + "个字节");
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
System.out.print("文件读取错误");
System.exit(-1);
}
}
}

3、OutputStream和Writer

  OutputStream里方法包含如下:

Modifier and Type Method Description
void close​()
Closes this output stream and releases any system resources associated with this stream.
void flush​()
Flushes this output stream and forces any buffered output bytes to be written out.
void write​(byte[] b)
Writes b.length bytes from the specified byte array to this output stream.
void write​(byte[] b, int off, int len)
Writes len bytes from the specified byte array starting at offset off to this output stream.                                                                                                                  
abstract void write​(int b)
Writes the specified byte to this output stream.

  Writer里包含方法如下:

Constructors 
Modifier Constructor Description
protected Writer​()
Creates a new character-stream writer whose critical sections will synchronize on the writer itself.
protected Writer​(Object lock)
Creates a new character-stream writer whose critical sections will synchronize on the given object.                                                                                                                                               
Modifier and Type Method Description
Writer append​(char c)
Appends the specified character to this writer.
Writer append​(CharSequence csq)
Appends the specified character sequence to this writer.
Writer append​(CharSequence csq, int start, int end)
Appends a subsequence of the specified character sequence to this writer.                                                                                                                      
abstract void close​()
Closes the stream, flushing it first.
abstract void flush​()
Flushes the stream.
void write​(char[] cbuf)
Writes an array of characters.
abstract void write​(char[] cbuf, int off, int len)
Writes a portion of an array of characters.
void write​(int c)
Writes a single character.
void write​(String str)
Writes a string.
void write​(String str, int off, int len)
Writes a portion of a string.
 package com.zyjhandsome.io;

 import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException; public class FileOutputStreamTest2 { public static void main(String[] args) {
// TODO Auto-generated method stub
int hasRead = 0;
byte[] bbuf = new byte[32];
FileInputStream fis = null;
FileOutputStream fos = null;
try {
fis = new FileInputStream("D:\\zhaoyingjun\\eclipse-workspace\\CollectionTest\\src\\com\\zyjhandsome\\io\\FileOutputStreamTest.java");
fos = new FileOutputStream("D:\\zhaoyingjun\\else\\Test\\FileOutputStreamTest_copy2.java");
while ((hasRead = fis.read(bbuf)) != -1)
{
fos.write(bbuf, 0, hasRead);
}
fis.close();
fos.close();
} catch (FileNotFoundException e2) {
// TODO Auto-generated catch block
e2.printStackTrace();
System.out.println("系统找不到指定问你件");
System.exit(-1);
}
catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
System.out.println("文件复制错误");
System.exit(-1);
}
System.out.println("文件已复制");
}
}

  如果希望直接输出字符串内容,则使用Writer会有更好的效果,如下程序所示:

 package com.zyjhandsome.io;

 import java.io.*;

 public class FileWriterTest {

     public static void main(String[] args) {
// TODO Auto-generated method stub
try {
FileWriter fw = new FileWriter("D:\\User_zhaoyingjun\\JavaSE\\Test\\FileWriterTest.txt");
fw.write("锦瑟 - 李商隐\r\n");
fw.write("锦瑟无端五十弦,一弦一柱思华年。\r\n");
fw.write("庄生晓梦迷蝴蝶,望帝春心托杜鹃。\r\n");
fw.write("沧海月明珠有泪,蓝田日暖玉生烟。\r\n");
fw.write("此情可待成追忆,只是当时已惘然。\r\n");
fw.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}

  Windows平台,使用\r\n换行;UNIX/Linux/BSD等平台,则使用\n作为换行符号。

Java 输入/输出——字节流和字符流的更多相关文章

  1. I/O(输入/输出)---字节流与字符流

    流: 分为输入流和输出流,输入/输出是相对计算机内存来说的,数据输入到内存是输入流,数据从内存中输出是输出流. 流对象构造的时候会和数据源联系起来. 数据源分为:源数据源和目标数据源.输入流联系的是源 ...

  2. java IO通过字节流,字符流 读出写入

    一:通过字节流操作数据的写入,读出 /** * 通过字节流写入和读出 * @param args */ public static String filePath = "G:" + ...

  3. java IO的字节流和字符流及其区别

    1. 字节流和字符流的概念    1.1 字节流继承于InputStream    OutputStream,    1.2 字符流继承于InputStreamReader    OutputStre ...

  4. JAVA基础之字节流与字符流

    个人理解: IO流就是将数据进行操作的方式,因为编码的不同,所以对文件的操作就产生两种.最好用字节流,为了方便看汉字等,(已经确定文字的话)可以使用字符流.每个流派也就分为输入和输出,这样就可以产生复 ...

  5. java IO之字节流和字符流-Reader和Writer以及实现文件复制拷贝

    接上一篇的字节流,以下主要介绍字符流.字符流和字节流的差别以及文件复制拷贝.在程序中一个字符等于两个字节.而一个汉字占俩个字节(一般有限面试会问:一个char是否能存下一个汉字,答案当然是能了,一个c ...

  6. JAVA中的字节流与字符流

    字节流与字符流的区别? 字节流与和字符流的使用非常相似,两者除了操作代码上的不同之外,是否还有其他的不同呢? 实际上字节流在操作时本身不会用到缓冲区(内存),是文件本身直接操作的,而字符流在操作时使用 ...

  7. java基础(23):字节流、字符流

    1. 字节流 在前面的学习过程中,我们一直都是在操作文件或者文件夹,并没有给文件中写任何数据.现在我们就要开始给文件中写数据,或者读取文件中的数据. 1.1 字节输出流OutputStream Out ...

  8. Java——I/O,字节流与字符流,BufferedOutputStream,InputStream等(附相关练习代码)

    I/O: I/O是什么? 在程序中,所有的数据都是以流的形式进行传输或者保存. 程序需要数据的时候,就要使用输入流读取数据. 程序需要保存数据的时候,就要使用输出流来完成. 程序的输入以及输出都是以流 ...

  9. Java中的字节流,字符流,字节缓冲区,字符缓冲区复制文件

     一:创建方式 1.建立输入(读)对象,并绑定数据源 2.建立输出(写)对象,并绑定目的地 3.将读到的内容遍历出来,然后在通过字符或者字节写入 4.资源访问过后关闭,先创建的后关闭,后创建的先关闭 ...

随机推荐

  1. 用VS2012建立core2.1网站项目后引用Microsoft.AspNetCore.Session不了

    做个.NET CORE的新项目,和往常一样,VS2017新建CORE项目(CORE2.1),NUGET引入session,结果引入不了,说什么版本不对应的,把SESSION降了一个版本,可以安装上了, ...

  2. 【Java】Java Queue的简介

    阻塞队列 阻塞队列有几个实现: ArrayBlockingQueue LinkedBlockingQueue PriorityBlockingQueue DelayQueue SynchronousQ ...

  3. 在android 上 使用 rxjava 入门篇

    什么是 rxJava? RxJava is a Java VM implementation of Reactive Extensions: a library for composing async ...

  4. Sword STL迭代器prev,next相关函数

    迭代器的头文件中定义了4个实现迭代器模板的函数模板. .advance(iterator,num):将迭代器iterator 移动了num个位置 .distance(iterator1,iterato ...

  5. php中json_decode及foreach使用总结

    <?php $arr=array(); //例子1 $json_str= '{"ret":"OK","questions":{ &qu ...

  6. Ubuntu 实践

    Ubuntu 安装中文支持 开始装的是Ubuntu Server,后来需要某些图形工具,所以装了个Gnome,没想到无论如何都显示不了中文,按照网上的方法试了一堆,装了Synaptic,KDE和GNO ...

  7. ABBYY OCR技术教电脑阅读缅甸语(上)

    缅甸联邦共和国,原名缅甸,是东南亚的一个国家,从1962年到2010年,缅甸一直被政变后上台的军政府统治,直至最近5年它才对外界开放,与其他国家建立了贸易与文化联系. 缅甸语由很多方言组成,但所有方言 ...

  8. spring与quartz定时器

    参考: http://www.iteye.com/topic/399980 http://www.cnblogs.com/xrab/p/5850186.html

  9. golang IO 流抽象与应用

    https://blog.csdn.net/pmlpml/article/details/82930191

  10. [Localization] MobileNet with SSD

    先来一波各版本性能展览: Pre-trained Models Choose the right MobileNet model to fit your latency and size budget ...