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.资源访问过后关闭,先创建的后关闭,后创建的先关闭 ...
随机推荐
- eclipse开发android入门学习
1.device窗体 查看android执行情况的窗体和DDMS内容一致 2.android.bat 在adb路径下执行adb操作,实现android系统 ...
- android源码 键盘消息处理机制
键盘消息处理模型: .WMS统一管理Window, 它包含了InputManager变量,其对应c++层的NativeInputManager2.c++层的NativeInputManager包含 i ...
- jpush在有网的情况下6002
网络处理问题. https://www.jpush.cn/qa/?qa=2476/%E7%BD%91%E7%BB%9C%E6%AD%A3%E5%B8%B8%E7%9A%84%E6%83%85%E5%8 ...
- ①Android NuPlayer播放框架
[时间:2016-09] [状态:Open] [关键词:android,nuplayer,开源播放器,播放框架,nuplayerdriver] 0 NuPlayer简介 Android2.3时引入流媒 ...
- chrome调试手机webview中页面
http://blog.csdn.net/freshlover/article/details/42528643 注: 1. 可以调试真机上页面(USB连接)和虚拟机上页面 2. 手机系统需要4.4+ ...
- Python_序列与映射的解包操作
解包就是把序列或映射中每个元素单独提取出来,序列解包的一种简单用法就是把首个或前几个元素与后面几个元素分别提取出来,例如: first, seconde, *rest = sequence 如果seq ...
- vmware-hostd.exe 占用443端口导致Apache无法正常启动?
问题: [Apache] Problem detected!16:23:19 [Apache] Port 443 in use by ""D:\vmware\VMware W ...
- Ubuntu系统搭建SVN服务器
Ubuntu系统搭建SVN服务器 参考地址:http://git.devzeng.com/blog/aliyun-ubuntu-svn-server.html 安装软件 依次在终端中执行下面的命令安装 ...
- [UFLDL] Linear Regression & Classification
博客内容取材于:http://www.cnblogs.com/tornadomeet/archive/2012/06/24/2560261.html Deep learning:六(regulariz ...
- bootstrap入门基础
1.字体 text-left text-center text-right text-lowercase 小写 text-uppercase 大写 text-capitalize 首字母大写 2.表格 ...