IO流(Input/Output)
寓为“开放中创新”(Innovation in the Open)
public File(String pathname) 以pathname为路径创建File对象,可以是绝对路径或者相对路径,如果 pathname是相对路径,则默认的当前路径在系统属性user.dir中存储。
- 绝对路径:是一个固定的路径,从盘符开始
- 相对路径:是相对于某个位置开始
说明:如果使用单元测试,文件相对路径为当前module
如果使用main()测试,文件相对路径为当前工程
路径分隔符
路径中的每级目录之间用一个路径分隔符隔开。
路径分隔符和系统有关:
- windows和DOS系统默认使用“\”来表示
- UNIX和URL使用“/”来表示
Java程序支持跨平台运行,因此路径分隔符要慎用
为了解决这个隐患,File类提供了一个常量: public static final String separator。根据操作系统,动态的提供分隔符
File 类的使用:常用方法
File类的获取功能
public String getAbsolutePath():获取绝对路径
public String getPath() :获取路径
public String getName() :获取名称
public String getParent():获取上层文件目录路径。若无,返回null
public long length() :获取文件长度(即:字节数)。不能获取目录的长度。
public long lastModified() :获取最后一次的修改时间,毫秒值
public String[] list() :获取指定目录下的所有文件或者文件目录的名称数组
public File[] listFiles() :获取指定目录下的所有文件或者文件目录的File数组
File类的重命名功能
public boolean renameTo(File dest):把文件重命名为指定的文件路径
File类的判断功能
public boolean isDirectory():判断是否是文件目录
public boolean isFile() :判断是否是文件
public boolean exists() :判断是否存在
public boolean canRead() :判断是否可读
public boolean canWrite() :判断是否可写
public boolean isHidden() :判断是否隐藏
File类的创建功能
public boolean createNewFile() :创建文件。若文件存在,则不创建,返回false
public boolean mkdir() :创建文件目录。如果此文件目录存在,就不创建了。
如果此文件目录的上层目录不存在,也不创建。
public boolean mkdirs() :创建文件目录。如果上层文件目录不存在,一并创建
注意事项:如果你创建文件或者文件目录没有写盘符路径,那么,默认在项目路径下。
File类的删除功能
public boolean delete():删除文件或者文件夹
删除注意事项:
Java中的删除不走回收站。
要删除一个文件目录,请注意该文件目录内不能包含文件或者文件目录
如下的两个方法适用于文件目录:
public String[] list() :获取指定目录下的所有文件或者文件目录的名称数组
public File[] listFiles() :获取指定目录下的所有文件或者文件目录的File数组
代码演示:
package com.jerry.java;
import java.io.File;
import java.io.IOException;
/**
* @author jerry_jy
* @create 2022-10-07 20:29
*/
public class FileTest {
public static void main(String[] args) throws IOException {
File file = new File("D:" + File.separator + "2.txt");
System.out.println("**********创建文件*********");
System.out.println(file.createNewFile());//false
System.out.println("**********获取绝对路径*********");
System.out.println(file.getAbsolutePath());//D:\2.txt
System.out.println("**********获取名称*********");
System.out.println(file.getName());//2.txt
System.out.println("**********获取文件长度(即:字节数)。不能获取目录的长度*********");
System.out.println(file.length());//0
System.out.println("**********获取最后一次的修改时间,毫秒值*********");
System.out.println(file.lastModified());//1665148556505
System.out.println("**********判断是否是文件目录*********");
System.out.println(file.isDirectory());//false
System.out.println("**********判断是否是文件*********");
System.out.println(file.isFile());//true
System.out.println("**********判断是否存在*********");
System.out.println(file.exists());//true
System.out.println("**********判断是否可读*********");
System.out.println(file.canRead());//true
System.out.println("**********判断是否可写*********");
System.out.println(file.canWrite());//true
System.out.println("**********判断是否隐藏*********");
System.out.println(file.isHidden());//false
System.out.println("**********创建文件。若文件存在,则不创建,返回false*********");
System.out.println(new File("D:" + File.separator + "3.txt").createNewFile());//false
System.out.println("**********删除文件或者文件夹*********");
System.out.println(file.delete());//true
File dir1 = new File("D:/IOTest/dir1");
if (!dir1.exists()) { // 如果D:/IOTest/dir1不存在,就创建为目录
dir1.mkdir();
}
// 创建以dir1为父目录,名为"dir2"的File对象
File dir2 = new File(dir1, "dir2");
if (!dir2.exists()) { // 如果还不存在,就创建为目录
dir2.mkdirs();
}
File dir4 = new File(dir1, "dir3/dir4");
if (!dir4.exists()) {
dir4.mkdirs();
}
// 创建以dir2为父目录,名为"test.txt"的File对象
File file1 = new File(dir2, "test.txt");
if (!file1.exists()) { // 如果还不存在,就创建为文件
file1.createNewFile();
}
}
/*
public boolean renameTo(File dest):把文件重命名为指定的文件路径
比如:file1.renameTo(file2)为例:
要想保证返回true,需要file1在硬盘中是存在的,且file2不能在硬盘中存在。
*/
@Test
public void test1(){
File file1 = new File("hello.txt");
File file2 = new File("D:\\io\\hi.txt");
boolean renameTo = file2.renameTo(file1);
System.out.println(renameTo);
}
File file = new File("D:\\io\\dir1\\dir3\\dir4\\dir5");
String[] list = file.list();//获取该目录下的String类型的名字
for (String s : list) {
System.out.println(s);//2.txt
}
File[] files = file.listFiles();//获取该目录下的File数组
for (File f : files) {
System.out.println(f);//D:\io\dir1\dir3\dir4\dir5\2.txt
}
}
IO流原理及流的分类
按操作数据单位不同分为:字节流(8 bit)(InputStream,OutputStream),字符流(16 bit) (Reader,Writer)
- 按数据流的流向不同分为:输入流,输出流
- 按流的角色的不同分为:节点流,处理流

* 二、流的体系结构
* 抽象基类 节点流(或文件流) 缓冲流(处理流的一种)
* InputStream FileInputStream (read(byte[] buffer)) BufferedInputStream (read(byte[] buffer))
* OutputStream FileOutputStream (write(byte[] buffer,0,len) BufferedOutputStream (write(byte[] buffer,0,len) / flush()
* Reader FileReader (read(char[] cbuf)) BufferedReader (read(char[] cbuf) / readLine())
* Writer FileWriter (write(char[] cbuf,0,len) BufferedWriter (write(char[] cbuf,0,len) / flush()

程序中打开的文件 IO 资源不属于内存里的资源,垃圾回收机制无法回收该资源,所以应该显式关闭文件 IO 资源。
FileInputStream 从文件系统中的某个文件中获得输入字节。FileInputStream 用于读取非文本数据之类的原始字节流。要读取字符流,需要使用 FileReader
FileRead–读取字符流文件
@Test
public void testFileReader() {
FileReader fileReader = null;
try {
//1.实例化File类的对象,指明要操作的文件
File file = new File("hello.txt");
//2.提供具体的流
fileReader = new FileReader(file);
//3.数据的读入
//read():返回读入的一个字符。如果达到文件末尾,返回-1
int data;
while ((data = fileReader.read()) != -1) {
System.out.print((char) data);//这里记得一定要强转为char类型,不然读出来就是ASCII
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
//4.流的关闭操作
if (fileReader != null) {
fileReader.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
//对read()操作升级:使用read的重载方法
@Test
public void testFileReader1() {
FileReader fileReader = null;
try {
//1.File类的实例化
File file = new File("hello.txt");
//2.FileReader流的实例化
fileReader = new FileReader(file);
//3.读入的操作
//read(char[] cbuf):返回每次读入cbuf数组中的字符的个数。如果达到文件末尾,返回-1
char[] cbuf = new char[5];
int len;
while ((len = fileReader.read(cbuf)) != -1) {
// System.out.print(cbuf);
//方式一:
//错误的写法
// for(int i = 0;i < cbuf.length;i++){
// System.out.print(cbuf[i]);
// }
//正确的写法
// for(int i = 0;i < len;i++){
// System.out.print(cbuf[i]);
// }
//方式二:
//错误的写法,对应着方式一的错误的写法
// String str = new String(cbuf);
// System.out.print(str);
//正确的写法
String str = new String(cbuf, 0, len);
System.out.print(str);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (fileReader != null) {
fileReader.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
FileWrite
/*
从内存中写出数据到硬盘的文件里。
说明:
1. 输出操作,对应的File可以不存在的。并不会报异常
2.
File对应的硬盘中的文件如果不存在,在输出的过程中,会自动创建此文件。
File对应的硬盘中的文件如果存在:
如果流使用的构造器是:FileWriter(file,false) / FileWriter(file):对原有文件的覆盖
如果流使用的构造器是:FileWriter(file,true):不会对原有文件覆盖,而是在原有文件基础上追加内容
*/
@Test
public void testFileWriter() {
FileWriter fileWriter = null;
try {
//1.提供File类的对象,指明写出到的文件
File file = new File("hello1.txt");
fileWriter = new FileWriter(file, false);
//3.写出的操作
fileWriter.write("I hava a dream!");
fileWriter.write("人需要有一个梦想!");
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
//4.流资源的关闭
if (fileWriter != null) {
fileWriter.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
FileReaderFileWriter
@Test
public void testFileReaderFileWriter() {
FileReader fileReader = null;
FileWriter fileWriter = null;
try {
//1.创建File类的对象,指明读入和写出的文件
File srcFile = new File("hello.txt");
File destFile = new File("hello2.txt");
//2.创建输入流和输出流的对象
fileReader = new FileReader(srcFile);
fileWriter = new FileWriter(destFile);
//3.数据的读入和写出操作
char[] cbuf = new char[5];
int len;
while ((len = fileReader.read(cbuf)) != -1) {
fileWriter.write(cbuf, 0, len);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (fileReader != null) {
fileReader.close();
}
} catch (IOException e) {
e.printStackTrace();
}
try {
if (fileWriter != null) {
fileWriter.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
FileInputStream–读取字节流文件
定义文件路径时,注意:可以用“/”或者“\”。
在写入一个文件时,如果使用构造器FileOutputStream(file),则目录下有同名文 件将被覆盖。
如果使用构造器FileOutputStream(file,true),则目录下的同名文件不会被覆盖, 在文件内容末尾追加内容。
在读取文件时,必须保证该文件已存在,否则报异常。
字节流操作字节,比如:.mp3,.avi,.rmvb,mp4,.jpg,.doc,.ppt , .excel
字符流操作字符,只能操作普通文本文件。最常见的文本文 件:.txt,.java,.c,.cpp 等语言的源代码。尤其注意.doc,excel,ppt这些不是文本文件。
/**
* 测试FileInputStream和FileOutputStream的使用
* <p>
* 结论:
* 1. 对于文本文件(.txt,.java,.c,.cpp),使用字符流处理
* 2. 对于非文本文件(.jpg,.mp3,.mp4,.avi,.doc,.ppt,excel...),使用字节流处理
*/
//使用字节流FileInputStream处理文本文件,可能出现乱码。
@Test
public void testFileInputStream() {
FileInputStream fis = null;
try {
File file = new File("hello.txt");
fis = new FileInputStream(file);
byte[] buffer = new byte[5];
int len;
while ((len = fis.read(buffer)) != -1) {
System.out.println(new String(buffer, 0, len));//读取字符流文件已经出现了乱码
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (fis != null) {
fis.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
FileInputOutputStream
/*
实现对图片的复制操作
*/
@Test
public void testFileInputOutputStream() {
FileInputStream fis = null;
FileOutputStream fos = null;
try {
File srcFile = new File("java.jpg");
File destFile = new File("java1.jpg");
fis = new FileInputStream(srcFile);
fos = new FileOutputStream(destFile);
byte[] buffer = new byte[5];
int len;
while ((len = fis.read(buffer)) != -1) {
fos.write(buffer, 0, len);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (fos != null) {
fos.close();
}
} catch (IOException e) {
e.printStackTrace();
}
try {
if (fis != null) {
fis.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
字节流进行指定路径下大文件的复制
//指定路径下文件的复制
public void copyFile(String srcPath, String destPath) {
FileInputStream fis = null;
FileOutputStream fos = null;
try {
File srcFile = new File(srcPath);
File destFile = new File(destPath);
fis = new FileInputStream(srcFile);
fos = new FileOutputStream(destFile);
byte[] buffer = new byte[1024];
int len;
while ((len = fis.read(buffer)) != -1) {
fos.write(buffer, 0, len);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (fos != null) {
fos.close();
}
} catch (IOException e) {
e.printStackTrace();
}
try {
if (fis != null) {
fis.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
@Test
public void testCopyFile(){
long start = System.currentTimeMillis();
String srcPath = "E:\\0课程资料\\密码学\\1.mp4";
String destPath = "E:\\0课程资料\\密码学\\1_1.mp4";
copyFile(srcPath, destPath);
long end = System.currentTimeMillis();
System.out.println("复制操作花费的时间为:" + (end - start));//2619ms
}
BufferedStream
为了提高数据读写的速度,Java API提供了带缓冲功能的流类,在使用这些流类 时,会创建一个内部缓冲区数组,缺省使用8192个字节(8Kb)的缓冲区。

缓冲流要“套接”在相应的节点流之上,根据数据操作单位可以把缓冲流分为:
- BufferedInputStream 和 BufferedOutputStream
- BufferedReader 和 BufferedWriter
注意:
当读取数据时,数据按块读入缓冲区,其后的读操作则直接访问缓冲区
当使用BufferedInputStream读取字节文件时,BufferedInputStream会一次性从 文件中读取8192个(8Kb),存在缓冲区中,直到缓冲区装满了,才重新从文件中 读取下一个8192个字节数组。
向流中写入字节时,不会直接写到文件,先写到缓冲区中直到缓冲区写满, BufferedOutputStream才会把缓冲区中的数据一次性写到文件里。使用方法 flush()可以强制将缓冲区的内容全部写入输出流
关闭流的顺序和打开流的顺序相反。只要关闭最外层流即可,关闭最外层流也 会相应关闭内层节点流
flush()方法的使用:手动将buffer中内容写入文件
如果是带缓冲区的流对象的close()方法,不但会关闭流,还会在关闭流之前刷 新缓冲区,关闭后不能再写出

实现非文本文件的复制
/**
* 处理流之一:缓冲流的使用
* <p>
* 1.缓冲流:
* BufferedInputStream
* BufferedOutputStream
* BufferedReader
* BufferedWriter
* <p>
* 2.作用:提供流的读取、写入的速度
* 提高读写速度的原因:内部提供了一个缓冲区
* <p>
* 3. 处理流,就是“套接”在已有的流的基础上。
*/
@Test
public void BufferedStreamTest() {
BufferedInputStream bis = null;
BufferedOutputStream bos = null;
try {
//1.造文件
File srcFile = new File("java.jpg");
File destFile = new File("java2.jpg");
//2.造流
//2.1 造节点流
FileInputStream fis = new FileInputStream(srcFile);
FileOutputStream fos = new FileOutputStream(destFile);
//2.2 造缓冲流
bis = new BufferedInputStream(fis);
bos = new BufferedOutputStream(fos);
//3.复制的细节:读取、写入
byte[] buffer = new byte[10];
int len;
while ((len = bis.read(buffer)) != -1) {
bos.write(buffer, 0, len);
bos.flush();//刷新缓冲区
}
} catch (IOException e) {
e.printStackTrace();
} finally {
//4.资源关闭
//要求:先关闭外层的流,再关闭内层的流,带缓冲流的close()方法在关闭流之前会刷新缓冲区
try {
if (bos != null) {
bos.close();
}
} catch (IOException e) {
e.printStackTrace();
}
try {
if (bis != null) {
bis.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
//说明:关闭外层流的同时,内层流也会自动的进行关闭。关于内层流的关闭,我们可以省略.
// fos.close();
// fis.close();
}
实现文本文件的复制
/*
使用BufferedReader和BufferedWriter实现文本文件的复制
*/
@Test
public void testBufferedReaderBufferedWriter() {
BufferedReader br = null;
BufferedWriter bw = null;
try {
br = new BufferedReader(new FileReader(new File("dbcp.txt")));
bw = new BufferedWriter(new FileWriter(new File("dbcp_1.txt")));
//读写操作
//方式一:使用char[]数组
// char[] cbuf = new char[10];
// int len;
// while ((len=br.read(cbuf))!=-1){
// bw.write(cbuf, 0, len);
// bw.flush();
// }
//方式二:使用String
String data;
while ((data = br.readLine()) != null) {
//方法一:
// bw.write(data + "\n");//data中不包含换行符
//方法二:
bw.write(data);
bw.newLine();
}
} catch (IOException e) {
e.printStackTrace();
}finally {
try {
if (bw!=null){
bw.close();
}
} catch (IOException e) {
e.printStackTrace();
}
try {
if (br!=null){
br.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
BufferedStream实现文件复制的方法
//实现文件复制的方法
public void copyFileWithBuffered(String srcPath, String destPath) {
BufferedInputStream bis = null;
BufferedOutputStream bos = null;
try {
//1.造文件
File srcFile = new File(srcPath);
File destFile = new File(destPath);
//2.造流
//2.1 造节点流
FileInputStream fis = new FileInputStream(srcFile);
FileOutputStream fos = new FileOutputStream(destFile);
//2.2 造缓冲流
bis = new BufferedInputStream(fis);
bos = new BufferedOutputStream(fos);
//3.复制的细节:读取、写入
byte[] buffer = new byte[1024];
int len;
while ((len = bis.read(buffer)) != -1) {
bos.write(buffer, 0, len);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
//4.资源关闭
//要求:先关闭外层的流,再关闭内层的流
try {
if (bos != null) {
bos.close();
}
} catch (IOException e) {
e.printStackTrace();
}
try {
if (bis != null) {
bis.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
//说明:关闭外层流的同时,内层流也会自动的进行关闭。关于内层流的关闭,我们可以省略.
// fos.close();
// fis.close();
}
@Test
public void testCopyFileWithBuffered() {
long start = System.currentTimeMillis();
String srcPath = "E:\\0课程资料\\密码学\\1.mp4";
String destPath = "E:\\0课程资料\\密码学\\1_1.mp4";
copyFileWithBuffered(srcPath, destPath);
long end = System.currentTimeMillis();
System.out.println("复制操作花费的时间为:" + (end - start));//336
}
获取文本上每个字符出现的次数
/*
获取文本上每个字符出现的次数
提示:遍历文本的每一个字符;字符及出现的次数保存在Map中;将Map中数据写入文件
*/
/*
说明:如果使用单元测试,文件相对路径为当前module
如果使用main()测试,文件相对路径为当前工程
*/
@Test
public void testWordCount() {
FileReader fr = null;
BufferedWriter bw = null;
try {
HashMap<Character, Integer> map = new HashMap<>();
fr = new FileReader("dbcp.txt");
int data;
while ((data = fr.read()) != -1) {
char c = (char) data;
if (map.get(c) == null) {
map.put(c, 1);
} else {
map.put(c, map.get(c) + 1);
}
}
bw = new BufferedWriter(new FileWriter("WordCount.txt"));
Set<Map.Entry<Character, Integer>> entrySet = map.entrySet();
for (Map.Entry<Character, Integer> entry : entrySet) {
switch (entry.getKey()) {
case ' ':
bw.write("空格=" + entry.getValue());
break;
case '\t':
bw.write("tab键=" + entry.getValue());
break;
case '\r':
bw.write("回车=" + entry.getValue());
break;
case '\n':
bw.write("换行=" + entry.getValue());
break;
default:
bw.write(entry.getKey() + "=" + entry.getValue());
break;
}
bw.newLine();
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (bw != null) {
bw.close();
}
} catch (IOException e) {
e.printStackTrace();
}
try {
if (fr != null) {
fr.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
转换流
转换流提供了在字节流和字符流之间的转
Java API提供了两个转换流:
nputStreamReader:将InputStream转换为Reader
OutputStreamWriter:将Writer转换为OutputStream
字节流中的数据都是字符时,转成字符流操作更高效。
InputStreamReader
实现将字节的输入流按指定字符集转换为字符的输入流。
需要和InputStream“套接”。
构造器
- public InputStreamReader(InputStream in)
- public InputSreamReader(InputStream in,String charsetName)

//InputStreamReader的使用,实现字节的输入流到字符的输入流的转换
@Test
public void test1() {
InputStreamReader isr = null;
try {
FileInputStream fis = new FileInputStream("dbcp.txt");
isr = new InputStreamReader(fis, "UTF-8");
char[] cbuf = new char[20];
int len;
while ((len = isr.read(cbuf)) != -1) {
System.out.println(new String(cbuf, 0, len));
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (isr != null) {
isr.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
OutputStreamWriter
实现将字符的输出流按指定字符集转换为字节的输出流。
需要和OutputStream“套接”。
构造器
- public OutputStreamWriter(OutputStream out)
- public OutputSreamWriter(OutputStream out,String charsetName)
/*
此时处理异常的话,仍然应该使用try-catch-finally
综合使用InputStreamReader和OutputStreamWriter
*/
@Test
public void test2() throws Exception {
//1.造文件、造流
File file1 = new File("dbcp.txt");
File file2 = new File("dbcp_gbk");
FileInputStream fis = new FileInputStream(file1);
FileOutputStream fos = new FileOutputStream(file2);
InputStreamReader isr = new InputStreamReader(fis, "UTF-8");
OutputStreamWriter osw = new OutputStreamWriter(fos, "GBK");
//2.读写过程
char[] cbuf = new char[20];
int len;
while ((len= isr.read(cbuf))!=-1){
osw.write(cbuf, 0, len);
}
//3.关闭资源
osw.close();
isr.close();
}
字符集
* 字符集
* ASCII:美国标准信息交换码。
* 用一个字节的7位可以表示。
* ISO8859-1:拉丁码表。欧洲码表
* 用一个字节的8位表示。
* GB2312:中国的中文编码表。最多两个字节编码所有字符
* GBK:中国的中文编码表升级,融合了更多的中文文字符号。最多两个字节编码
* Unicode:国际标准码,融合了目前人类使用的所有字符。为每个字符分配唯一的字符码。所有的文字都用两个字节来表示。
* UTF-8:变长的编码方式,可用1-4个字节来表示一个字符。
其他类型的流(不重要)
标准输入、输出流
System.in的类型是InputStream
System.out的类型是PrintStream,其是OutputStream的子类 FilterOutputStream 的子类
从键盘输入字符串,要求将读取到的整行字符串转成大写输出。然后继续进行输入操作,
直至当输入“e”或者“exit”时,退出程序。
方法一:使用Scanner实现,调用next()返回一个字符串
方法二:使用System.in实现。System.in ---> 转换流 ---> BufferedReader的readLine()
// 方式一:采用scanner.next()方法
while (true){
System.out.println("从键盘输入字符串:");
Scanner scanner = new Scanner(System.in);
String str = scanner.next();
if ("e".equalsIgnoreCase(str)||"exit".equalsIgnoreCase(str)){
System.out.println("程序结束!");
break;
}
System.out.println(str.toUpperCase());
}
// 方式二:采用BufferedReader
BufferedReader br = null;
while (true) {
try {
InputStreamReader isr = new InputStreamReader(System.in);
br = new BufferedReader(isr);
System.out.println("从键盘输入字符串:");
String str = br.readLine();
if ("e".equalsIgnoreCase(str) || "exit".equalsIgnoreCase(str)) {
System.out.println("程序结束!");
break;
}
System.out.println(str.toUpperCase());
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (br != null) {
br.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
打印流
实现将基本数据类型的数据格式转化为字符串输出
打印流:PrintStream和PrintWriter
- 提供了一系列重载的print()和println()方法,用于多种数据类型的输出
- PrintStream和PrintWriter的输出不会抛出IOException异常
- PrintStream和PrintWriter有自动flush功能
- PrintStream 打印的所有字符都使用平台的默认字符编码转换为字节。 在需要写入字符而不是写入字节的情况下,应该使用 PrintWriter 类。
- System.out返回的是PrintStream的实例
@Test
public void test2() {
PrintStream ps = null;
try {
FileOutputStream fos = new FileOutputStream(new File("D:\\io\\1.txt"));
ps = new PrintStream(fos, true);
if (ps != null) {
System.out.println(ps);
}
for (int i = 0; i <= 255; i++) {
System.out.println((char) i);
if (i % 50 == 0) {
System.out.println();
}
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} finally {
if (ps != null) {
ps.close();
}
}
}
数据流
为了方便地操作Java语言的基本数据类型和String的数据,可以使用数据流。
数据流有两个类:(用于读取和写出基本数据类型、String类的数据)
- DataInputStream 和 DataOutputStream
- 分别“套接”在 InputStream 和 OutputStream 子类的流上
DataInputStream中的方法
boolean readBoolean() byte readByte()
char readChar() float readFloat()
double readDouble() short readShort()
long readLong() int readInt()
String readUTF() void readFully(byte[] b)
DataOutputStream中的方法
@Test
public void test3() {
DataOutputStream dos = null;
try {
dos = new DataOutputStream(new FileOutputStream(new File("data.txt")));
dos.writeUTF("杰瑞");
dos.flush();
dos.writeInt(123);
dos.flush();
dos.writeBoolean(true);
dos.flush();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (dos != null) {
dos.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
将文件中存储的基本数据类型变量和字符串读取到内存中,保存在变量中。
注意点:读取不同类型的数据的顺序要与当初写入文件时,保存的数据的顺序一致!
@Test
public void test4() {
DataInputStream dis=null;
try {
dis = new DataInputStream(new FileInputStream("data.txt"));
String name = dis.readUTF();
int age = dis.readInt();
boolean isMale = dis.readBoolean();
System.out.println("name: " + name);
System.out.println("age: " + age);
System.out.println("Male: " + isMale);
} catch (IOException e) {
e.printStackTrace();
}finally {
try {
if (dis!=null){
dis.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}