Java 输入/输出——字节流和字符流
1、流的分类
(1)输入流和输出流(划分输入/输出流时是从程序运行所在内存的角度来考虑的)
输入流:只能从中读取数据,而不能向其写入数据。
输出流:只能向其写入数据,而不能从中读取数据。
输入流主要由InputStream和Reader作为基类,输出流主要由OutputStream和Writer作为基类。它们都是抽象基类,无法直接创建实例。
(2)字节流和字符流
字节流和字符流的用法几乎完全一样,区别在于字节流和字符流操作的数据单元不同——字节流操作的数据单元是8-bit的字节,而字符流操作的数据单元是16-bit的字符。
字节流主要由InputStream和OutputStream作为基类,而字符流则主要由Reader和Writer作为基类。
(3)节点流和处理流
可以从/向一个特定的IO设备(如磁盘、网络)读/写数据的流,称为节点流,节点流也被称为低级流。
处理流则用于对一个已经存在的流进行连接或封装,通过封装后的流来实现数据读/写功能。处理流也被称为高级流。
2、InputStream和Reader
在InputStream里包含你的方法如下:
| 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里包含方法如下:
| 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里包含方法如下:
| 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 输入/输出——字节流和字符流的更多相关文章
- I/O(输入/输出)---字节流与字符流
流: 分为输入流和输出流,输入/输出是相对计算机内存来说的,数据输入到内存是输入流,数据从内存中输出是输出流. 流对象构造的时候会和数据源联系起来. 数据源分为:源数据源和目标数据源.输入流联系的是源 ...
- java IO通过字节流,字符流 读出写入
一:通过字节流操作数据的写入,读出 /** * 通过字节流写入和读出 * @param args */ public static String filePath = "G:" + ...
- java IO的字节流和字符流及其区别
1. 字节流和字符流的概念 1.1 字节流继承于InputStream OutputStream, 1.2 字符流继承于InputStreamReader OutputStre ...
- JAVA基础之字节流与字符流
个人理解: IO流就是将数据进行操作的方式,因为编码的不同,所以对文件的操作就产生两种.最好用字节流,为了方便看汉字等,(已经确定文字的话)可以使用字符流.每个流派也就分为输入和输出,这样就可以产生复 ...
- java IO之字节流和字符流-Reader和Writer以及实现文件复制拷贝
接上一篇的字节流,以下主要介绍字符流.字符流和字节流的差别以及文件复制拷贝.在程序中一个字符等于两个字节.而一个汉字占俩个字节(一般有限面试会问:一个char是否能存下一个汉字,答案当然是能了,一个c ...
- JAVA中的字节流与字符流
字节流与字符流的区别? 字节流与和字符流的使用非常相似,两者除了操作代码上的不同之外,是否还有其他的不同呢? 实际上字节流在操作时本身不会用到缓冲区(内存),是文件本身直接操作的,而字符流在操作时使用 ...
- java基础(23):字节流、字符流
1. 字节流 在前面的学习过程中,我们一直都是在操作文件或者文件夹,并没有给文件中写任何数据.现在我们就要开始给文件中写数据,或者读取文件中的数据. 1.1 字节输出流OutputStream Out ...
- Java——I/O,字节流与字符流,BufferedOutputStream,InputStream等(附相关练习代码)
I/O: I/O是什么? 在程序中,所有的数据都是以流的形式进行传输或者保存. 程序需要数据的时候,就要使用输入流读取数据. 程序需要保存数据的时候,就要使用输出流来完成. 程序的输入以及输出都是以流 ...
- Java中的字节流,字符流,字节缓冲区,字符缓冲区复制文件
一:创建方式 1.建立输入(读)对象,并绑定数据源 2.建立输出(写)对象,并绑定目的地 3.将读到的内容遍历出来,然后在通过字符或者字节写入 4.资源访问过后关闭,先创建的后关闭,后创建的先关闭 ...
随机推荐
- Mongodb嵌套文档的改动-利用数组改动器更新数据
初学mongodb的可能和我一样有个疑问.mongodb是文档型的,那么假设一个文档嵌套另外一个文档,假设对这个嵌套文档进行增删改查呢. 就像例如以下这样:.怎样对auther里面的name进行增删改 ...
- 基于mindwave脑电波进行疲劳检测算法的设计(2)
上文讲到的是保证硬件的接通.接下来是用C语言在它提供的API接口进行连接. 在网盘中下载MindSet Development Tools这个开发包.这个目录下MindSet Development ...
- 利用OCR识别扫描的jpg、tif文件的文字
第一步:下载老马哥的从 office和sharepoint 提取出来的注册表和dll http://115.com/file/dpa4qrt2 或者直接安装office和sharepoint2007 ...
- (转-经典-数据段)C++回顾之static用法总结、对象的存储,作用域与生存期
转自:https://blog.csdn.net/ab198604/article/details/19158697相关知识补充:https://www.cnblogs.com/rednodel/p/ ...
- Go Revel - Cache(缓存)
revel在服务器端提供了`cache`库用以低延迟的存储临时数据.它缓存那些需要经常访问数据库但是变化不频繁的数据,也可以实现用户会话的存储. ##有效期 一下三种方法为缓存元素设置过期时间: 1. ...
- Android 测试入门之---Monkey test
这周重点学习的也是Android monkey test 的一些相关知识,也对其进行了初步的操作和试验.讲学习资料整理如下 : Monkey是一个命令行工具 ,可以运行在模拟器里或实际设备中.它向系统 ...
- Linux磁盘概念及其管理工具fdisk
Linux磁盘概念及其管理工具fdisk [日期:2016-08-27] 来源:Linux社区 作者:chawan [字体:大 中 小] 引言:冯诺依曼体系中的数据存储器就是我们常说的磁盘或硬盘 ...
- H3C ER6300 + 两台 H3C S5120 组网举例
组网需求: 1.H3C ER6300 作出口路由.防火墙及Qos限速等功能(ER6300 配置LAN口 192.168.30.254默认网关) 2.H3C S5120 两台配置相同VLAN10 VLA ...
- Ubuntu Linux 解决 bash ./ 没有那个文件或目录 的方法
Ubuntu Linux 解决 bash ./ 没有那个文件或目录 的方法 经常在ubuntu 64位下运行 ./xxx 会跳出来说没有这个文件或者目录,但是ls看又有这个文件,很是奇怪. 其实原因很 ...
- css - 兼容适配坑点总结(。。。)
1. transform为代表的这些css3属性一定要写-webkit-,不然低版本(目前遇到的是8)的苹果,不支持. 2. x的适配 /* x */ @media only screen and ( ...