Java输入和输出
文章目录
- **Java输入和输出**
- 01-File类-非流式-文件特征与管理
- 一、常用的构造方法
- 二、File常用方法
- 02-命令行参数
- 03-标准输入输出
- 04-流
- 一、概念普及
- 二、IO框架
- 三、IO流分类
- 四、常用方法
- 1、InputStream类常用方法
- 2、OutputStream类常用方法
- 3、FileInputStream类使用格式
- 4、FileOutputStream类使用格式
- 5、BufferedInputSteam类 /BufferedOutputStream类-缓冲输入输出流
- 6、Writer类常用方法
- 7、Writer类常用方法
- 8、InputStream与Reader、OutputStream与Writer差别
- 9、InputStreamReader类使用格式
- 10、OutputStreamReader类使用格式
- 11、FileReader类使用格式
- 12、File Writer类使用格式
- 13、BufferedReader类 和 BufferedWriter类使用格式
- 14、PrintStream 类使用格式
- 15、PrintWriter类使用格式
- 16、RandomAccessFile类使用格式
- 17、过滤器流简单介绍
- 17、ObjectIntput 和 ObjectOutput 类的使用格式
前言:Java中的I/O操作是指使用Java进行输入输出操作,Java所有I/O机制都是基于数据流进行,
流IO 特性:简单好用,效率低下;
块IO特性:效率高效,操作复杂;
Java的IO模型 设计优秀,使用Decorator模式,按功能划分stream,动态使用;
如,需要具有双缓冲的文件输入流,组合使用 FileInputStream,和 BufferedInputStream;
数据流
电脑中数据存储方式:外存、内存、缓存;
存储量:外存>内存>缓存
读写速度:缓存>内存>外存
数据流使得输入和输出独立于设备
Java IO体系主要分成几个层次、几个类、几个接口
io包中 有 5个类:File、OutputStream、InputStream、Reader、Writer
1个接口:Serializable
三部分:
流式部分——IO主体部分
非流式部分——File类、RandomAccessFile类、FileDescriptor类等
其他类——文件读取部分 与安全相关类 SerializablePermission类,
——本地操作系统相关的文件系统类 FileSystem类等;
01-File类-非流式-文件特征与管理
File类是一个与流概念无关的类,file类的对象可以获取文件及其文件所在的目录、文件的长度等信息;
还有 RandomAccessFile类 (从文件任意位置存取操作)和FileDescriptor类等等
这个类主要 用于文件或目录的描述信息读取和使用 不是流式类的子类,因为不负责数据的输入和输出,是专门用来管理磁盘文件与目录的;
一、常用的构造方法
No.1 File (String pathname)
该构造方法 通过的文件路径字符串来创建一个新的File实例对象
在当前的目录下创建
pathname:文件路径字符串,包括文件名称,就是字符换转化为 抽象的路径
new File (pathname)
No.2 File(String path,String filsname)
该构造方法,根据指定的父路径字符串和子路径字符串(包括文件名称)创建File类的实例对象
path:父路径字符串 必须事前存在,否则异常;
filename: 子路径字符串,不可为空值
new File(path,filename)
No.3File(File file,String filename) 不存在 自动创建
该构造方法根据指定的File类的父路径和字符串类型的子路径(包含文件名称)创建File类的实例对对象
file:父路径对象
filename:子路径字符串
new file (file,filename)
No.4 File(String url)
该构造方法 根据指定的url路径创建File类的实例对象
url :网路统一定位符
new file(url)
二、File常用方法
方法名称 | 方法描述 | 返回类型 |
---|---|---|
getName() | 获取文件或目录的名字 | String |
getParent() | 获取文件的父路径字符串 | String |
getPath() | 获取文件的相对路径字符串 | String |
getAbsolutePath() | 获取文件的绝对路径字符串 | String |
length() | 获取文件的长度 | int |
lastModified() | 获取文件的最后修改日期 | long |
exists() | 判断文件或目录是否存在 | boolean |
isDirectory() | 判断是不是文件夹类型 | boolean |
canRead() | 判断文件是否可读 | boolean |
canWrite | 判断文件是否可被写入 | boolean |
canExecute() | 判断文件是否可以被执行 | boolean |
isFile() | 判断文件是否是一个正常的文件,而非目录 | boolean |
isAbsolute() | 判断是不是绝对路径 | boolean |
isHidden() | 判断文件是否时隐藏文件 | boolean |
delete() | 删除文件或目录,删除成功返回true | boolean |
mkdir() | 创建文件夹,创建成功返回true | boolean |
mkdirs() | 创建文件夹,路径中包含所有父文件夹和子文件夹,创建成功返回true | boolean |
creatNewFile() | 仅当该文件不存在时,原地创建一个新的空文件 | static File |
creatTempFile(String prefix,String suffix,File directory) | 在指定目录创建空文件,使用给定的前缀和后缀字符串生成其名称 | static File |
list() | 返回字符串数组,命名由该抽象路径名表示的目录中的文件和目录 | String[] |
listFiles() | 返回抽象路径名数组,表示由该路径表示的目录中的文件 | File[] |
renameTo(File dest) | 重命名由此抽象路径名表示的文件 | boolean |
toString() | 返回次抽象路径名字符串 | String |
02-命令行参数
Java程序可通过命令行参数 与外界进行有限的信息交换,
规定与标准输入、输出设备进行信息交换的方式
public class TestArgs {
public static void main(String[] args) {
for (int i = 0; i < args.length; i++) {
System.out.println("args[" + i + "] is <" + args[i] + ">");
}
}
//运行命令:java TestArgs Java C VB
/**
运行结果
args[0] is <java>
args[1] is <C>
args[2] is <VB>
03-标准输入输出
Java系统自带标准数据流:java.lang.System
java.lang.System;
public final class System extends Object{
static PrintStream err; //标准错误流 输出
static InputStream in; //标准输入流 键盘输入流
static PrintStream out; //标准输入流 显示器输出
}
System类无法创建对象,只能直接使用它的三个静态成员;其次,每当main方法被执行时,自动生成三个上述对象;
标准输出流 System.out 数据类型PrintStream
方法有 :void print(参数)
void println(参数)
标准错误流 详情查看API
标准输入流 System.in 数据类型时InputStream
方法有: int read() 返回ASCII码,若返回 -1,说明没有读取到任何字节数;
int read(byte[] b)读入多个字节到缓存区b中返回值时读入的字节数
import java.io.*;
public class StandardInputOutput{
public static void main(String args[]){
int b;
try{
System.out.println("Please input: ");
while ((b =System.in.read()) != -1){ //判断是否读取数据到缓存区
System.out.print((char)b); //将转换的数据 转换回来
}
}catch (IOException e){
System.out.println(e.toString())
}
}
}
//实现键盘输入,把输入的内容存储到某文件中
import java.io.*;
public class Example01{
public static void main(String args[]){
File file = new File("C:\\","Example01.txt");
try{
if(!file.exists())
file.creatNewFile();
InputStreamReader isr = new InputStreamReader(System.in);// 读取键盘输入,用 Reader子类建立
BufferedReader br = new BufferedReader(isr); //建立缓存输入对象
System.out.println("请输入:");
String str = br.readLine();
System.out.print("您输入的数据是:"+str);
FileWriter fw = new FileWriter(file,true); //建立文件输出对象
BufferedWriter bw = new BufferedWriter(fw); //创建缓存输出对象
bw.write(str); //调用缓存输出方法
br.close();
bw.close();
}catch (IOEception IOe){
IOe.printStackTrace();
}
}
}
04-流
一、概念普及
流(stream) 是一组 有序的数据序列,
根据操作类型,分为 输入流和输出流,
根据操作数据类型,分为字节流和字符流;
所以 分为==字节输入流(InputStream)、字节输出流(OutputStream)、字符输入流(Reader)、字符输出流(Writer)==这四大抽象类 不可被实例化
字节流 字符流 输入流 InputStream Reader 输出流 OutputStream Writer 输入流的指向称为源,程序从指向源的输入流中读取源中的数据。
将数据从外存中读取到内存中称为输入流
多为 打印在屏幕上、
当程序需要读取数据时,就会开启一个通向数据源的流,这个数据源可以是文件、内存、网络连接,
将数据从内存写入外存中称为输出流
输出流 的指向 是字节要去的目的地,程序通过向输出流中写入数据 把信息传递到目的地。
程序需要写入数据时,就会开启一个通向目的地的流
输入流 InputStream 不关心数据源来自何种设备(键盘、文件、网络)
输出流OutputStream不关心数据目的地是何种设备(键盘、文件、网络)
Java程序通过文件 可以与外界进行任意数据形式的信息交换
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-4klZalqQ-1663071613347)(C:\Users\hp\AppData\Roaming\Typora\typora-user-images\image-20200919164040932.png)]
二、IO框架
JDK1.4版本引入新I/O类库,位于java.nio包中,利用通道和缓冲区等提高I/O操作的效率
三、IO流分类
一、按I/O类型来总体分类:
1. Memory 1)从/向内存数组读写数据: CharArrayReader、 CharArrayWriter、ByteArrayInputStream、ByteArrayOutputStream
2)从/向内存字符串读写数据 StringReader、StringWriter、StringBufferInputStream
2.Pipe管道 实现管道的输入和输出(进程间通信): PipedReader、PipedWriter、PipedInputStream、PipedOutputStream
3.File 文件流。对文件进行读、写操作 :FileReader、FileWriter、FileInputStream、FileOutputStream
4. ObjectSerialization 对象输入、输出 :ObjectInputStream、ObjectOutputStream
5.DataConversion数据流 按基本数据类型读、写(处理的数据是Java的基本类型(如布尔型,字节,整数和浮点数)):DataInputStream、DataOutputStream
6.Printing 包含方便的打印方法 :PrintWriter、PrintStream
7.Buffering缓冲 在读入或写出时,对数据进行缓存,以减少I/O的次数:BufferedReader、BufferedWriter、BufferedInputStream、BufferedOutputStream
8.Filtering 滤流,在数据进行读或写时进行过滤:FilterReader、FilterWriter、FilterInputStream、FilterOutputStream过
9.Concatenation合并输入 把多个输入流连接成一个输入流 :SequenceInputStream
10.Counting计数 在读入数据时对行记数 :LineNumberReader、LineNumberInputStream
11.Peeking Ahead 通过缓存机制,进行预读 :PushbackReader、PushbackInputStream
12.Converting between Bytes and Characters 按照一定的编码/解码标准将字节流转换为字符流,或进行反向转换(Stream到Reader,Writer的转换类):InputStreamReader、OutputStreamWriter
二、按数据来源(去向)分类:
1.File(文件): FileInputStream, FileOutputStream, FileReader, FileWriter
2.byte[]:ByteArrayInputStream, ByteArrayOutputStream
3.Char[]: CharArrayReader, CharArrayWriter
4.String: StringBufferInputStream, StringReader, StringWriter
5.网络数据流:InputStream, OutputStream, Reader, Writer
四、常用方法
1、InputStream类常用方法
- FileInputStream 是把该文件作为InputStream,实现对文件的读取
- ByteArrayInputStream:把内存中的一个缓冲区作为InputStream使用
- StringBufferInputStream:把一个String对象作为InputStream
- PipedInputStream:实现pipe的概念,主要在线程中使用
- SequenceInputStream:把多个InputStream合并为一个InputStream
特征:所有字节输入流的父类,
字节流 是以字节为单位来处理数据,字节流不会对数据进行任何转换,用来处理二进制的数据
方法名称 | 功能描述 |
---|---|
public abstract int read() | 读取一个byte的数据,返回是高位补0的int ASCII值,返回值为-1,说明没有读取到任何字节,读取工作自动结束 |
public int read(byte b[])() | 读取b.length个字节的数据放到b数组中,返回值是读取的字节数, |
public int read(byte b[],int off,int len)() | 从输入流中最多读取len个字节的数据,存放到偏移量为off的b数组中 |
public int available() | 返回当前输入流的数据读取方法可以读取的有效字节数,若输入阻塞,当前线程将被挂起,如果InputStream对象调用这个方法的话,它只会返回0,这个方法必须由继承InputStream类的子类对象调用才有用, |
public long skip(long n)() | 忽略输入流中的n个字节,返回值是实际忽略的字节数,跳过一些字节来读取 |
public int close() | 关闭当前输入流,释放任何与之相关的系统资源 |
mark(int readlimit) | 在输入数据流中加入标记 |
markSupported() | 测试输入流中是否支持标记 |
2、OutputStream类常用方法
- ByteArrayOutputStream:把信息存入内存中的一个缓冲区
- FileOutputStream:把信息存入文件中
- PipedOutputStream:实现pipe概念,主要用于线程中使用
- SequenceOutputStream:把多个OutputStream合并为一个OutputStream
方法名称 | 功能描述 |
---|---|
public abstract void write(int b) | 将int转换为byte类型,把低字节写入到输出流中 |
public void write(byte b[ ]) | 将数组b中的数据写入写入到当前输出流 |
public void write(byte b[ ], int off, int len) | 将数组byte[] 中下标off开始的len长度的数据写入到当前的输出流中 |
public void flush( ) | 刷新当前输出流,并强制写入所有缓冲的字节数据,清空缓冲区 |
public void close( ) | 关闭当前输出流,并释放有关系统资源 |
流结束的判断:方法read()的返回值为-1,readLine()的返回值为null
3、FileInputStream类使用格式
FileInputStream 使用read()方法一次读入一个字节,并以int类型返回,
使用read(byte[])方法时读入到一个byte类型的数组中,在整个文件读取完成前,该byte数组当做缓冲区,
使用方法格式
'''Java
File file = new File("d:\\abc.txt");
FileInputStream fi =new FileInputStream(file);
//或者一步到位
FileInputStream fi = new FileInputStream("d:\\abc.txt");
'''Java
package io;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
/**
* FileInputStream 使用例子:
* 在E:\必须删除存有"Example.txt"文件,此文件的内容为“This is my book!”。创建一个File对象
* 然后创建 文件字节输入流对象 fis,
* 从输入流中读取文件"Example.txt"的信息
* @author hp
*
*/
public class FileDemo02 {
public static void main(String[] args) throws IOException{
// TODO 自动生成的方法存根
try {
File file = new File("E:\\必须删除","Example.txt");
FileInputStream fis = new FileInputStream(file);
//以上两步直接 写成 FileInputStream fis = new FileInputStream("C:\Example.txt");
byte[] bytes = new byte[512];
int i ;
System.out.println("The content of "+file.getName()+" is: ");
while((i = fis.read(bytes, 0, 512))>0) {
//在循环中读取输入流中的字节数据
String s = new String(bytes,0,i);
System.out.println(s);
//因为 read()方法返回的时当前某个字节的ACSII值,需要转换为字符;另一种方式是
fis.close();
// System.out.print((char)i);发现失败,暂时搁置,到时解决
}
}catch(IOException e) {
System.out.println(e.toString());
}
}
}
4、FileOutputStream类使用格式
处理以文件作为数据输出目的的数据流,从内存区读数据入文件
构造方法01:
File file01 = new File();
FileOutputStream fos = new FileOutputStream(file01)//覆盖原有内容
FileOutputStream fos = new FileOutputStream(file01,true);// 追加内容
file :File文件类型的实例对象,在file后面,加true会对原有内容进行追加,不加true会将原有内容覆盖
构造方法02:
FileOutputStream fos = new FileOutputStream(filename)
filename :文件的相对路径和绝对路径
构造方法03:
FileDescriptor() fd=new FileDescriptor();
FileOutputStream f2=new FileOutputStream(fd);构造函数将 FileDescriptor()对象作为其参数。
'''Java
package io;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
/**
* 创建一个 File类的对象,
* 首先,判断此配置文件是否存在;
* 若不存在,调用creatNewFile()方法创建一个空文件,
* @author hp
*
*/
public class FileDemo03 {
public static void main(String[] args) {
// TODO 自动生成的方法存根
File file = new File("E:\\","Example2.txt");
int b;
byte[] bytes = new byte[512];
System.out.println("请输入你想存入文本的内容:");
try {
if(!file.exists())
file.createNewFile();
b = System.in.read(bytes); //把键盘输入的字符存入到bytes数组中 这一步很关键
FileOutputStream fos = new FileOutputStream(file,true);
fos.write(bytes, 0, b);
fos.close();
}catch (IOException e) {
e.printStackTrace();
}
}
}
5、BufferedInputSteam类 /BufferedOutputStream类-缓冲输入输出流
计算机访问外部设备非常耗时。访问外存的频率越高,造成CPU闲置的概率就越大。为了减少访问外存的次数,应该在一次对外设的访问中,读写更多的数据。为此,除了程序和流节点间交换数据必需的读写机制外,还应该增加缓冲机制。缓冲流就是每一个数据流分配一个缓冲区,一个缓冲区就是一个临时存储数据的内存。这样可以减少访问硬盘的次数,提高传输效率。
BufferedInputStream:当向缓冲流写入数据时候,数据先写到缓冲区,待缓冲区写满后,系统一次性将数据发送给输出设备。
BufferedOutputStream :当从向缓冲流读取数据时候,系统先从缓冲区读出数据,待缓冲区为空时,系统再从输入设备读取数据到缓冲区。
1)将文件读入内存:
将BufferedInputStream与FileInputStream相接
FileInputStream in=new FileInputStream( “file1.txt ” );
BufferedInputStream bin=new BufferedInputStream( in);
2)将内存写入文件:
将BufferedOutputStream与 FileOutputStream相接
FileOutputStreamout=new FileOutputStream(“file1.txt”);
BufferedOutputStream bin=new BufferedInputStream(out);
3)键盘输入流读到内存
将BufferedReader与标准的数据流相接
InputStreamReader sin=new InputStreamReader (System.in) ;
BufferedReader bin=new BufferedReader(sin);
'''Java
import java.io.*;
public class ReadWriteToFile {
public static void main(String args[]) throws IOException {
InputStreamReader sin = new InputStreamReader(System.in);
BufferedReader bin = new BufferedReader(sin);
FileWriter out = new FileWriter("myfile.txt");
BufferedWriter bout = new BufferedWriter(out);
String s;
while ((s = bin.readLine()).length() > 0) {
bout.write(s, 0, s.length()); // 理解一下这一步的操作
}
}
}
/*程序说明:
从键盘读入字符,并写入到文件中BufferedReader类的方法:String readLine()
作用:读一行字符串,以回车符为结束。
BufferedWriter类的方法:bout.write(String s,offset,len)
作用:从缓冲区将字符串s从offset开始,len长度的字符串写到某处。
*/
6、Writer类常用方法
Java中字符 是采用Unicode标准,一个字符16位,使用2个字节表示;
用于读取 字符流,子类必须实现的方法只有 read(char[] ,int a,int b
和 close();
但是 ,多数子类重写此处定义的一些方法,以提供更高的效率和其他功能;
**1) FileReader 😗*与FileInputStream对应
主要用来读取字符文件,使用缺省的字符编码,有三种构造函数:
(1)将文件名作为字符串 :
FileReader f=new FileReader(“c:/temp.txt”);
(2)构造函数将File对象作为其参数。
File f=new file(“c:/temp.txt”);
FileReader f1=new FileReader(f);
(3) 构造函数将FileDescriptor对象作为参数
FileDescriptor() fd=new FileDescriptor()
FileReader f2=new FileReader(fd);
(1) 用指定字符数组作为参数:CharArrayReader(char[])
(2) 将字符数组作为输入流:CharArrayReader(char[], int, int)
读取字符串,构造函数如下: public StringReader(String s);
**2) CharArrayReader:**与ByteArrayInputStream对应
3) StringReader : 与StringBufferInputStream对应
4) InputStreamReader
从输入流读取字节,在将它们转换成字符:Public inputstreamReader(inputstream is);
5) FilterReader: 允许过滤字符流
protected filterReader(Reader r);
**6) BufferReader 😗*接受Reader对象作为参数,并对其添加字符缓冲器,使用readline()方法可以读取一行。
Public BufferReader(Reader r);
方法名称 | 功能描述 |
---|---|
public int read() throws IOException | 读取一个字符,返回值为读取的字符 |
public abstract int read(char cbuf[],int off,int len) throws IOException | 读取len个字符,从数组cbuf[]的下标off处开始存放,返回值为实际读取的字符数量,该方法必须由子类实现 |
public int read(char cbuf[]) throws IOException | 读取一系列字符到数组cbuf[]中,返回值为实际读取的字符的数量 |
reset() | 将当前输入流重新定位到最后一次调用mark()方法时的位置 |
skip(long n) | 跳过参数n指定的字符数量,并返回所跳过字符的数量 |
close() | 关闭该流并释放系统资源,关闭后,无法调用其他方法 |
mark()?未考证 | 标记 |
7、Writer类常用方法
写入字符流的抽象类。子类必须实现的方法仅有 write(char[], int, int)、flush() 和 close()。但是,多数子类将重写此处定义的一些方法,以提供更高的效率和/或其他功能。
Reader类能够将输入流中采用其他编码类型的字符转换为Unicode字符,然后在内存中为其分配内存
Writer类能够将内存中的Unicode字符转换为其他编码类型的字符,再写到输出流中。
1) FileWrite: 与FileOutputStream对应
将字符类型数据写入文件,使用缺省字符编码和缓冲器大小。
Public FileWrite(file f);
2) CharArrayWrite:与ByteArrayOutputStream对应 ,将字符缓冲器用作输出。
Public CharArrayWrite();
3) PrintWrite:生成格式化输出
public PrintWriter(outputstream os);
4) filterWriter:用于写入过滤字符流
protected FilterWriter(Writer w);
5) PipedWriter:与PipedOutputStream对应
6) StringWriter:无与之对应的以字节为导向的stream
方法名称 | 功能操作 |
---|---|
public void write(int c) throws IOException | 将整型值c的低16位写入输出流 |
public void write(char[] cbuf) throws IOException | 将字符数组cbuf[]写入输出流 |
public abstract void write(char cbuf[],int off,int len) throws IOException | 将字符数组cbuf[]中的从索引为off的位置处开始的len个字符写入输出流 |
public void write(String str) throws IOException | 将字符串str中的字符写入输出流 |
public void write(String str,int off,int len) throws IOException | 将字符串str 中从索引off开始处的len个字符写入输出流 |
flush( ) | 刷空输出流,并输出所有被缓存的字节 |
close() | 关闭流 |
8、InputStream与Reader、OutputStream与Writer差别
InputStream和OutputStream类处理的是字节流,数据流中的最小单位是字节(8个bit)
Reader与Writer处理的是字符流,在处理字符流时涉及了字符编码的转换问题
'''Java
import java.io.*;
public class EncodeTest {
private static void readBuff(byte [] buff) throws IOException {
ByteArrayInputStream in =new ByteArrayInputStream(buff);
int data;
while((data=in.read())!=-1) System.out.print(data+" ");
System.out.println(); in.close();
}
public static void main(String args[]) throws IOException {
System.out.println("内存中采用unicode字符编码:" );
char c='好';
int lowBit=c&0xFF;
int highBit=(c&0xFF00)>>8;
System.out.println(""+lowBit+" "+highBit);
String s="好";
System.out.println("本地操作系统默认字符编码:");
readBuff(s.getBytes());
System.out.println("采用GBK字符编码:");
readBuff(s.getBytes("GBK"));
System.out.println("采用UTF-8字符编码:");
readBuff(s.getBytes("UTF-8"));
}
}
9、InputStreamReader类使用格式
InputStreamReader 是字节流通向字符流的桥梁;
可以根据指定的编码方式,将字节输入流转化为字符输入流;
常见的编码方式名称有 GBK、GB2312、UTF-8
构造方法01: InputStreamReader(InputStream is)
File file = new File();
FileInputStream fis = new FileInputStream(file);
InputStreamReader isr = new InputStreamReader(fis);
构造方法02:InputStreamReader(InputStream is,String cname)
File file = new File();
FileInputStream fis = new FileInputStream(file);
InputStreamReader isr = new InputStreamReader(fis,“UTF-8”);
常用的方法:
read() | read(char[],int off,int len) | ready()报告此流是否已准备 | getEncoding()返回此流使用的字符编码的名称 | close() |
'''Java
//使用FileInputStream 类中的例子
package io;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
/**
* FileInputStream 使用例子:
* 在E:\必须删除存有"Example.txt"文件,此文件的内容为“This is my book!”。创建一个File对象
* 然后创建 文件字节输入流对象 fis,
* 从输入流中读取文件"Example.txt"的信息
* @author hp
*
*/
public class FileDemo02 {
public static void main(String[] args) throws IOException{
// TODO 自动生成的方法存根
try {
File file = new File("E:\\必须删除","Example.txt");
FileInputStream fis = new FileInputStream(file);
//以上两步直接 写成 FileInputStream fis = new FileInputStream("C:\Example.txt");
InputStreamReader isr = new InputStreamReader(fis);
byte[] bytes = new byte[512];
int i ;
System.out.println("The content of "+file.getName()+" is: ");
while((i = isr.read())>0) {
System.out.print((char)i);
//这里就是和文件字节输入流不一样的地方了;
//在文件字节输入流中,read方法参数式数组,而这里是read方法没有参数
//这里 read返回的是数值,通过对数值的转换来实现读取字符操作
}catch(IOException e) {
System.out.println(e.toString());
}
}
}
10、OutputStreamReader类使用格式
OutputStreamReader 是字节流通向字符流的桥梁;
可以根据指定的编码方式,将字节输出流转化为字符输出流;
构造方法01: OutputStreamReader(OututStream is)
File file = new File();
FileOututStream fos = new FileOututStream(file);
OututStreamReader osr = new OututStreamReader(fos);
构造方法02:InputStreamReader(InputStream is,String cname)
File file = new File();
FileOutputStream fos = new FileOututStream(file);
OutputStreamReader osr = new OutputStreamReader(fos,“UTF-8”);
常用方法
write(int char) | write(String str,int off,int len) | write(char[] cb,int off,int len) | flush() | close() |
// 时间 9-19 晚上 9点整
'''Java
package io;
import java.io.*;
/**
* 创建两个File类的对象,分别判断 两个文件 是否存在,
* 若不存在,则新建
* 从其中的一个文件“Example03.txt”,中读取数据,复制到文件“Example04.txt”中,最终使
* 文件Example04,txt中的内容与Example03.txt的内容相同
* @author hp
*
*/
public class FileDemo04 {
public static void main(String[] args) {
// TODO 自动生成的方法存根
File filein = new File("E:\\","Example03.txt");
File fileout = new File("E:\\","Example04.txt");
FileInputStream fis;
try {
if(!filein.exists())
filein.createNewFile();
if(!fileout.exists())
fileout.createNewFile();
fis = new FileInputStream(filein);
InputStreamReader isr = new InputStreamReader(fis);
FileOutputStream fos = new FileOutputStream(fileout,true);
OutputStreamWriter osw = new OutputStreamWriter(fos);
int is;
while((is=isr.read()) !=-1) {
osw.write(is);
//这里和文件字节输出流不一样,read方法没有参数,而且返回的是数值
}
isr.close();
osw.close();
}catch(IOException e) {
e.printStackTrace();
}
}
}
11、FileReader类使用格式
构造方法01:
File file = new File();
FileReader fr = new FileReader(file);
new FileReader(File file);参数 file 是File类实例对象
构造方法02:
FileReader fr = new FileReader(“文件路径”)
new FileReader(String filePath)
'''Java
//利用File Reader读取文件Example01.txt的内容,输出到控制台上
try{
File file = new File("C:\\","Example01.txt");
FileReader fr = new FileReader(file); //创建文件字符输入流
char[] data = new char[512];
int rs = 0;
while((rs = fr.read(data))>0){ //在循环中读取数据
String str = new String(data,0,rs); //字符数组转换为字符串
System.out.println(str);
}catch (IOEception IOe){
e.printStackTrace();
}
}
12、File Writer类使用格式
构造方法01:
File file = new File();
FileWriter fw = new FileWriter(file);
new FileWriter(File file);
构造方法02:
FileWriter fw = new FileWriter(“文件路径”);
new FileWriter(String filePath);
'''Java
//首先,判断Example02.txt文件是否存在,若不存在,则新建
//然后将Example03.txt的内容复制到Example02.txt中;
try{
File file = new File("C:\\","Example02.txt");
if(!file.exists())
file.creatNewFile();
FileWriter fw = new FileWriter(file);
FileReader fr = new FileReader("C:\\Example03.txt");
int is; //记得这个传递参数是数字类型
while((is = fr.read()) != -1){
fw.write(is);
}
fr.close();
fw.close();
}catch (Eception e){
e.printStackTrace();
}
13、BufferedReader类 和 BufferedWriter类使用格式
BufferedReader类构造方法:
File file = new File();
FileReader fr = new FileReader(file);
BufferedReader br = new BufferedReader(fr);
BufferedReader类是Reader类的子类,使用该类可以以行为单位 进行读取数据
传入的参数是Reader类即可
BufferedReader类中 有ReaderLine()方法,Reader类中没有此方法
BufferedWriter类构造方法:
File file = new File();
FileWriter fw = new FileWriter(file);
BufferedWriter bw = new BufferedWriter(fw);
BufferedWriter 类是Writer的字类,使用该类可以以行为单位 进行写入数据
传入的参数是Writer类即可
BuferedWriter类中提供newLine()方法,Writer类中没有此方法,该方法是换行标记;
'''Java
// 使用BuferedReader实现对数据的读取
FileReader fr;
try{
fr = new FileReader("C:\\Exampel04.txt");
BufferedReader br = new BufferedReader(fr);
String aline;
While((aline = br.readLine())!= null){
String str = new String(aline);
System.out.println(str);
}
}catch(Exception e){
e.printStrackTrace();
}
'''Java
//使用BufferedWriter实现对数据的写入
File file = new File("C:\\Example01.txt");
FileWriter fs ;
try{
fs = new FileWriter(file,true);
BufferedWriter bw = new BufferedWriter(fs);
bw.write("Example");
bw.newLine(); //换行操作
bw.write("Example");
bw.close();
}catch(IOEception IOe){
IOe.printStrackTrace();
}
'''Java
//使用BufferedReader和 BufferedWriter 将Example05.txt文件内容传入到文件Example06.txt中
//
import java.io.*;
public class Exaple06{
public static void main(String args[]){
try{
FileReader fr;
fr = new FileReader("C:\\Example05.txt");
BufferedReader br = new BufferedReader(fr);
File file = new File("C:\\Example06.txt");
FileWriter fw = new FileWriter(file);
BufferedWriter bw = new BufferedWriter(fw);
String str = null;
while((str=br.readLine())!= null){
bw.write(str);
bw.newLine();
}
br.close();
bw.close();
}catch(IOEception IOe){
IOe.printStackTrace;
}
}
}
14、PrintStream 类使用格式
PrintStream 是 打印输出流,直接输出各种类型 的数据,
构造方法:
PrintStream (OutputStream out)
方法名称 | 功能描述 |
---|---|
print(String str) | 打印字符串 |
print(char[]ch) | 打印一个字符数组 |
print(object obj) | 打印一个对象 |
println(String str) | 打印一个字符串并结束该行 |
println(char[] ch) | 打印一个字符数组并结束该行 |
println(object obj) | 打印一个对象并结束该行 |
'''Java
//创建一File类对象,随机输出100以内的5个数,并把5个数保存到 Example07.txt文件中
import java.io.*;
import java.util.Random;
public class Example07{
public static void main(String args[]){
PrintStream ps;
try{
File file = new File("E:\\","Example07.txt");
if(!file.exists)
file.creatNewFile();
ps = new PrintStream (new FileOutputStream(file))
Random r = new Random();
int rs = 0;
for(int i=0;i<5;i++){
rs = r.nextInt(100);
ps.println(rs+'\t');
}
ps.close();
file.delete();//
}catch(IOEception IOe){
IOe.printStrackTrace()
}
}
}
15、PrintWriter类使用格式
PrintWriter是打印输出流,该流把Java语言的内构类型 以字符表示形式 传送 到相应的输出流中,可以以文本的形式浏览,
构造方法01:
new PrintWriter (Writer out)
参数是Writer类的实例对象
构造方法02:
new PrintWriter(OutputStream os)
参数是OutputStream 类的实例对象
方法名称 | 功能描述 |
---|---|
print(String str) | 将字符串型数据写至输出流 |
print(int i) | 将整形数据写至输出流 |
flush() | 强制性地将缓冲区中的数据写至输出流 |
println(String str) | 将字符串和换行符写至输出流 |
println(int i) | 将整形数据和换行符写至输出流 |
println() | 将换行符写至输出流 |
'''Java
// 使用PrintWriter 实现对文件的复制功能
File filein = new File();
File fileout = new File();
try{
BufferedReader br = new BufferedReader(new FileReader(filein));
PrintWriter pw = new PrintWriter(new FileWriter (fileout));
int b;
whilt((b=br.read()) != -1){ //返回是数值型
pw.write((char)b); // 将其转化为字符型
}
br.close();
pw.close();
}catch (Exception e){
e.printStrackTrace();
}
16、RandomAccessFile类使用格式
RandomAccessFile类可以读取任意位置数据的文件。不是输入流的子类,也不是输出流的子类;
构造方法01:
RandomAccessFile(String name,String mode);
name:和系统相关的文件名
mode:用来决定创建的流对文件的访问权利,r,rw,rws,rwd, r表示只读,rw表示 可读写,rws表示同步写入,rwd表示将更新同步写入
RandomAccessFile(File file, String mode);
file:
mode:
方法名称 功能描述 getFilePointer() 返回此文件中的当前偏移量 length() 获取文件长度 seek(long pos) 设置文件指针位置 readByte() 从文件中读取一个字节 readChar() 从文件中读取一个字符 readInt() 从文件中读取一个int值 readLine() 从文件中读取一个文本行 readBoolean() 从文件中读取一个布尔值 readUTF() 从文件中读取一个UTF字符串 writeInt(int v) 向文件写入一个int值 write(byte[] bytes) 把bytes.length个字节写入到文件 writeChars(String str) 向文件中写入一个作为字符数据的字符串 writeUTF(String str) 向文件中写入一个UTF字符串 close() 关闭文件
'''Java
//显示文件本身源代码执行过程
try{
File file = new File("文件路径");
RandomAccessFile raf = new RandomAccessFile(file,"rw");//创建随机访问文件为读写
long filepoint =0; // 定义文件总长度变量
long filelen = rad.length(); //获取文件的长度
while(filepoint < filelen){
String str = raf.readLine(); //从文件中读取数据
System.out.println(str);
filepoint = raf.getFilePointer(); //返回操作后的当前偏移量
}
raf.close();
}catch(IOException IOe){
IOe.printStrackTrace();
}
'''Java
// C盘存在某文件,创建Int型数组,,把Int型数组写入到该文件中,然后倒序输出这些数据
import java.io.*;
public class Example{
public static void main (String args[]){
int[] bytes = {1,2,3,4,5};
try{
RandomAccessFile raf = new RandomAccessFile("文件路径","rw");
for(int i =0;i<bytes.length;i++){
raf.writeInt(bytes[i]);
}
for(int i = bytes.length-1;i>=0i--){
raf.seek(i*4); //int型数据占据4个字节
System.out.println(raf.readLine());
}
raf.close();
}catch(IOException IOe){
IOe.printStrackTrace();
}
}
}
17、过滤器流简单介绍
Filter Stream(过滤器流)是为某种目的过滤字节或字符的数据流,
基本输入流提供 的读取方法,只能用来读取字节或字符;
过滤器流能够读取整数值、双精度值、字符串,但需要一个过滤器类 来包装流
DataInputStream 和DataOutputStream 分别FileInputStream 和FileOutputStream类的子类;
分别实现DataInput 和DataOutput接口;
该接口定义 独立于具体及其的带有格式的读写操作 ,从而实现对Java中国的不同基本类型数据的读写;
'''Java
//从文件中读取数据,先创建 一个FileInputStream类的对象;
//然后,把把该类传递给它
FileInputStream fis = new FileInputStream ("文件路径");
DataInputStream dis= new DataInputStream(fis);
int i = dis.readInt();
dis.close();
//把数据写入文件中 ,先创建 一个OutputStream类的对象
FileOutputStream fos = new FileOutputStream("文件路径");
DataOutputStream dos = new DataOutputStream(fos);
dos.writeBytes("");
dos.close();
常见的过滤器:
BufferedReader :对留的数据加以处理再输出
LineNumberReader:缓冲流,记录读入的行数,创建方法:int getLineNumber()
PrintWriter:将输出导入某种设备
17、ObjectIntput 和 ObjectOutput 类的使用格式
前言导入:对象序列化操作(Object Serialization)
程序运行需要保存文件,对基本数据类型 简单保存到文件中,程序下次启动,可读取文件中的数据初始化程序;
对于复杂的对象类型,若 需要永久保存,使用上述解决方法会复杂,需要把对象中的不同属性分解成基本类型,分别保存,再次运行,建立新对象,从文件中读取与对象有关的数据,使用这些数据为对象进行初始化;
**优化:**使用对象输入输出流实现对象序列化,可以直接存取对象
将对象存入一个流 被称为序列化,从一个流中读取对象,称为反序列化;
ObjectIntput 和 ObjectOutput 接口分别继承 了DataInput 和DataOutput接口,**提供对基本数据类型和对象序列化的方法。**使用序列化功能可以方便的写入或存取数据
readObject():反序列化,读取数据,从输入流中获取序列化的对象数据,用这些数据生成新的Java对象,该方法定义在ObjectInput接口中,
Object object = readObject() ;
object:Java对象
使用readObject()方法获取的序列化对象时Object类型,必须通过强行类型转换才能使用
writeObject():序列化,存入数据,从输出流(文件、网络、其他)定义在ObjectOutput接口中,
writeObject(object)
使用writeObject()方法 被序列化的对象必须实现java.io.Serialization接口,否则无法实现序列化