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.资源访问过后关闭,先创建的后关闭,后创建的先关闭 ...
随机推荐
- Socket网络编程--简单Web服务器(3)
上一小节已经实现了浏览器发送请求,然后服务器给出应答信息,然后浏览器显示出服务器发送过来的网页.一切看起来都是那么的美好.这一小节就准备实现可以根据地址栏url的不同来返回指定的网页.目前还不考虑带参 ...
- linux每日命令(39):lsof命令
lsof(list open files)是一个列出当前系统打开文件的工具.在linux环境下,任何事物都以文件的形式存在,通过文件不仅仅可以访问常规数据,还可以访问网络连接和硬件.所以如传输控制协议 ...
- Oracle同一个用户下启动多个数据库实例
oracle@yingxiang-testServer1 oradata]$ export ORACLE_SID=APPDB[oracle@yingxiang-testServer1 oradata ...
- 【6集iCore3_ADP触摸屏驱动讲解视频】6-5 底层驱动之SDRAM读写(下)
源视频包下载地址: 链接:http://pan.baidu.com/s/1jIC2LKy 密码:zyn3 银杏科技优酷视频发布区: http://i.youku.com/gingko8
- Java多线程系列——过期的suspend()挂起、resume()继续执行线程
简述 这两个操作就好比播放器的暂停和恢复. 但这两个 API 是过期的,也就是不建议使用的. 不推荐使用 suspend() 去挂起线程的原因,是因为 suspend() 在导致线程暂停的同时,并不会 ...
- 【Unity】ShareSDK、SMSSDK的基本使用与常见问题
概要 测试使用ShareSDK的一些常用功能.包括: 用微博帐号做第三方登录 获取用户的帐号详细信息 获取好友列表 分享功能 测试使用SMSSDK插件,包括: 导入插件,解决包冲突 短信登录功能:发验 ...
- Halcon 之dyn_threshold与threshold区别与用法
相同点:都是为了选择想要的灰度区域 dyn_threshold (OrigImage, MeanImage, SmallRaw, 3, 'light') //动态阈值分割 threshold()// ...
- [Bayes] openBUGS: this is not the annoying bugs in programming
Bayesian inference Using Gibbs Sampling 允许用户指定复杂的多层模型,并可使用MCMC算法来估计模型中的未知参数. We use DAGs to specify ...
- 12外观模式Facade
一.什么是外观模式 Facade模式也叫外观模式,是由GoF提出的 23种设计模式中的一种.Facade模式为一组具 有类似功能的类群,比如类库,子系统等等,提供一个一致的简单的界面.这个一致的简单的 ...
- 正确停掉 expdp 或 impdp
1.查看视图dba_datapump_jobs SQL> set line 200 SQL> select job_name,state from dba_datapump_jobs; J ...