1.字节流 FileInputStream、FileOutputStream
①FileInputStream
import java.io.FileInputStream; public class FileInputStreamDemo {
public static void main(String[] args) throws Exception {
FileInputStream in = new FileInputStream("D:\\a.txt");
// 构建一个字节数组作为缓冲区
byte[] bs = new byte[10];
// 定义一个变量来记录读取的字节个数
int len = -1;
while ((len = in.read(bs)) != -1) {
System.out.println(new String(bs, 0, len, "utf-8"));
}
in.close();
}
}
②FileOutputStream
import java.io.FileOutputStream; public class FileOutputStreamDemo {
public static void main(String[] args) throws Exception {
//true是追加。不加true,或者是false会新建并覆盖已有的。
FileOutputStream out = new FileOutputStream("D:\\a.txt", false);
// 字节流身上没有缓冲区
out.write("缓冲区".getBytes("utf-8")); //utf-8编码
out.write("abc".getBytes());
out.close();
}
}
关于流中的异常处理
1.将刘对象放在try之外声明并且赋值为null,放到try内初始化。
2.在关流之前需要判断流对象是否初始化成功(判断流对象是否为null)。
3.关流之后需要将流对象强制置为null,防止关流失败流对象依然占用文件。
4.需要在关流之前手动冲刷缓冲区以防关流失败导致一部分数据死在缓冲区中。
③用FileInputStream、FileOutputStream复制文件
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException; public class CopyFileDemo {
public static void main(String[] args) {
FileInputStream in = null;
FileOutputStream out = null;
try {
in = new FileInputStream("D:\\a.zip");
out = new FileOutputStream("C:\\a.zip");
// 构建一个字节数组作为缓冲区
byte[] bs = new byte[1024 * 1024 * 10];
// 定义一个变量来记录每次读取的字节个数
int len = -1;
while ((len = in.read(bs)) != -1) {
out.write(bs, 0, len);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e1){
e1.printStackTrace();
} finally{
if(in != null){
try {
in.close();
} catch (IOException e) {
e.printStackTrace();
} finally {
in = null;
}
}
if(out != null){
try {
out.close();
} catch (IOException e) {
e.printStackTrace();
} finally {
out = null;
}
}
}
}
}
2.转换流 InputStreamReader、OutputStreamWriter
①InputStreamReader 将字节转化为字符的流
import java.io.FileInputStream;
import java.io.InputStreamReader; public class InputStreamReaderDemo {
public static void main(String[] args) throws Exception {
// 底层靠的是FileInputStream
// 读取出来的是字节,但是展现的是字符---将字节转化为字符
InputStreamReader in = new InputStreamReader(new FileInputStream("D:\\test.txt"), "utf-8");
char[] cs = new char[3];
in.read(cs);
in.close();
System.out.println(cs);
}
}
②OutputStreamWriter 将字符转化为字节的流
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter; public class OutputStreamWriterDemo {
public static void main(String[] args) throws IOException {
// OutputStreamWriter将字符转化为字节的流
// 实际上是用FileOutputStream来写出数据
// 传入的参数是字符形式,但是最后以字节形式向外写出---字符转字节
OutputStreamWriter ow = new OutputStreamWriter(new FileOutputStream("D:\\test.txt"), "utf-8");
ow.write("转换流");
ow.close();
}
}
③用InputStreamReader、OutputStreamWriter改变文件的编码
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter; public class ChangeEncode {
public static void main(String[] args) {
changeEncode("srcTest.txt", "destTest.txt", "gbk", "utf-8");
System.out.println("over"); }
public static void changeEncode(String srcFile, String destFile, String srcEncodeType, String dstEncodeType){
InputStreamReader isr = null;
OutputStreamWriter osw = null; try {
isr = new InputStreamReader(new FileInputStream(srcFile),srcEncodeType);
osw = new OutputStreamWriter(new FileOutputStream(destFile),dstEncodeType);
char[] cs = new char[1024];
int len = 0;
while((len = isr.read(cs)) != -1){
osw.write(cs, 0, len);
osw.flush();
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if(isr != null){
try {
isr.close();
} catch (IOException e) {
e.printStackTrace();
} finally {
isr = null;
}
}
if(osw != null){
try {
osw.close();
} catch (IOException e) {
e.printStackTrace();
} finally {
osw = null;
}
}
}
}
}
效果:
3.字符流 FileReader,FileWriter
①FileReader
Demo1:单个字符读取
import java.io.FileReader; public class FileReaderDemo1 {
public static void main(String[] args) throws Exception {
// 创建了一个输入流对象指向了要读取的文件
FileReader reader = new FileReader("D:\\a.txt");
// 返回的是这字符所对应的编码
// int i = reader.read();
// 定义一个变量来存储读取的字符
int i = -1;
// 如果读取到文件的末尾,则返回一个-1
while ((i = reader.read()) != -1) {
System.out.println((char)i);
}
reader.close();
}
}
Demo2:多个字符读取
import java.io.FileReader; public class FileReaderDemo2 {
public static void main(String[] args) throws Exception {
FileReader reader = new FileReader("D:\\a.docx");
// 提供一个字符数组作为缓冲区
char[] cs = new char[20];
// 定义一个变量来记录每次读取到的字符个数
int i = -1;
// 如果读取到了末尾同样返回一个-1
// 返回本次读取到的字符个数
while ((i = reader.read(cs)) != -1) {
System.out.println(new String(cs, 0, i));
}
reader.close();
}
}
②FileWriter
import java.io.FileWriter;
import java.io.IOException; public class FileWriterDemo1 {
public static void main(String[] args) throws IOException {
FileWriter writer = new FileWriter("D:\\a.txt");
writer.write("def");
writer.flush();
writer.close();
writer = null;
System.out.println(writer);
}
}
③用FileReader,FileWriter复制文件
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException; public class CopyFile {
public static void main(String[] args) {
FileReader reader = null;
FileWriter writer = null;
try {
reader = new FileReader("D:\\a.txt");
writer = new FileWriter("D:\\b.txt");
char[] cs = new char[10];
int i = -1;
while ((i = reader.read(cs)) != -1) {
writer.write(cs, 0, i);
}
writer.flush();
} catch (Exception e) {
e.printStackTrace();
} finally {
if (reader != null) {
try {
reader.close();
} catch (IOException e) {
e.printStackTrace();
} finally {
reader = null;
}
}
if (writer != null) {
try {
writer.close();
} catch (IOException e) {
e.printStackTrace();
} finally {
writer = null;
}
}
}
}
}
CopyFile字符流
4.缓冲流 BufferedReader、BufferedWriter
①BufferedReader
import java.io.BufferedReader;
import java.io.FileReader; public class BufferedReaderDemo {
public static void main(String[] args) throws Exception {
// 实际上读取文件的是FileReader,BufferedReader的作用是在FileReader的基础上来提供一个缓冲区
BufferedReader br = new BufferedReader(new FileReader("D:\\aaa.txt"));
// BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream("D:\\a.txt")));
// 每次读取一行数据
String str = null;
while ((str = br.readLine()) != null) {
System.out.println(str);
}
// 关流: 要么只关外层的流,要么从里向外关
br.close();
}
}
②BufferedWriter
import java.io.BufferedWriter;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.OutputStreamWriter; public class BufferedWriterDemo {
public static void main(String[] args) throws Exception {
BufferedWriter bw = new BufferedWriter(new FileWriter("D:\\aaa.txt"));
// BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(new FileOutputStream("D:\\a.txt")));
bw.write("123");
bw.flush();
bw.close();
}
}
③用BufferedReader、BufferedWriter改变文件的编码
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter; public class ChangeEncode {
public static void main(String[] args) {
changeEncode("srcTest.txt", "destTest.txt", "gbk", "utf-8");
System.out.println("over"); }
public static void changeEncode(String srcFile, String destFile, String srcEncodeType, String dstEncodeType){
InputStreamReader isr = null;
BufferedReader br = null;
OutputStreamWriter osw = null;
BufferedWriter bw = null; try {
isr = new InputStreamReader(new FileInputStream(srcFile),srcEncodeType);
br = new BufferedReader(isr);
osw = new OutputStreamWriter(new FileOutputStream(destFile),dstEncodeType);
bw = new BufferedWriter(osw);
String line = null;
while((line = br.readLine()) != null){
bw.write(line);
bw.newLine();
}
} catch (Exception e) {
e.printStackTrace();
} finally{
if(br != null){
try {
br.close();
} catch (IOException e) {
e.printStackTrace();
} finally {
br = null;
}
}
if(bw != null){
try {
bw.close();
} catch (IOException e) {
e.printStackTrace();
} finally {
bw = null;
}
}
}
}
}
ChangeEncode
5.合并流 SequenceInputStream
将多个流放入一个Vector集合中,利用Vector的elements方法来获取一个Enumeration对象,再利用Enumeration对象来构建SequenceInputStream对象。
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.SequenceInputStream;
import java.util.Enumeration;
import java.util.Vector; public class SequenceInputStreamDemo {
public static void main(String[] args) throws Exception {
FileInputStream in1 = new FileInputStream("D:\\a.txt");
FileInputStream in2 = new FileInputStream("D:\\b.txt");
FileInputStream in3 = new FileInputStream("D:\\c.txt"); Vector<InputStream> v = new Vector<>();
v.add(in1);
v.add(in2);
v.add(in3);
// 将v转化为一个Enumeration对象
Enumeration<InputStream> e = v.elements();
// 构建合并流对象
SequenceInputStream sis = new SequenceInputStream(e);
// 创建一个输出流对象指向合并后的文件
FileOutputStream out = new FileOutputStream("D:\\test.txt"); byte[] bs = new byte[5];
int len = -1;
while ((len = sis.read(bs)) != -1) {
out.write(bs, 0, len);
}
sis.close();
out.close();
}
}
其它文件读写练习:
1.统计目录中java代码的行数
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException; public class CountCodeLine { public static void main(String[] args) {
File dir = new File(".\\src\\lianxi");
System.out.println(countCodeLine(dir));
}
//java中代码行数
public static int countCodeLine(File file){
if(file == null){
return 0;
}
if(!file.isDirectory()){
if(file.getName().endsWith(".java")){
return javaLine(file);
}
else
return 0;
}else{
int sum = 0;
File[] fs = file.listFiles();
for(File f : fs){
sum += countCodeLine(f);
}
return sum;
}
}
private static int javaLine(File file){
BufferedReader br = null;
int countLine = 0;
try {
br = new BufferedReader(new FileReader(file.getAbsolutePath()));
while ((br.readLine()) != null) {
countLine++;
} } catch (IOException e) {
e.printStackTrace();
}finally{
if(br != null){
try {
br.close();
} catch (IOException e) {
e.printStackTrace();
}finally{
br = null;
}
}
}
return countLine;
}
}
2.将文件切块保存
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.util.Properties;
import java.util.UUID; public class FileSplit {
public static void main(String[] args) throws Exception {
// 使用Properties来记录文件的切块
Properties p = new Properties(); File file = new File("D:\\a.avi");
FileInputStream in = new FileInputStream(file); // 定义一个变量来记录文件快的个数
int count = 0;
byte[] bs = new byte[1024 * 1024 * 5];
int len = -1;
while ((len = in.read(bs)) != -1) {
// 获取一个统一的值
int hash = UUID.randomUUID().toString().hashCode();
String h = Integer.toHexString(hash);
// 补足8位
int rest = 8 - h.length();
for (int i = 0; i < rest; i++) {
h = "0" + h;
}
// 产生对应的路径
String path = "D:\\split";
for (char c : h.toCharArray()) {
path = path + "\\" + c;
}
System.out.println(path);
// 产生目录
new File(path).mkdirs();
// 文件块的路径
path = path + "\\" + UUID.randomUUID().toString();
// 记录文件块的路径
p.setProperty("" + count, path);
count++;
// 将文件块放到目录里面
FileOutputStream out = new FileOutputStream(path);
out.write(bs, 0, len);
out.close();
}
p.setProperty("count", "" + count);
p.store(new FileOutputStream("a.properties"), null);
in.close();
}
}
拆分效果:
3.将切块的文件整合
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.SequenceInputStream;
import java.util.Properties;
import java.util.Vector; public class FileUnion {
public static void main(String[] args) throws Exception {
Properties p = new Properties();
p.load(new FileInputStream("a.properties"));
// 文件切得块数
int count = Integer.parseInt(p.getProperty("count"));
Vector<InputStream> v = new Vector<>();
// 创建输入流指向对应的文件快
for (int i = 0; i < count; i++) {
v.addElement(new FileInputStream(p.getProperty(i + "")));
}
// 创建一个输出流来指向新文件
FileOutputStream out = new FileOutputStream("C:\\a.avi");
SequenceInputStream sis = new SequenceInputStream(v.elements());
// 读取数据
byte[] bs = new byte[1024 * 1024 * 1];
int len = -1;
while((len = sis.read(bs)) != -1){
out.write(bs, 0, len);
}
out.close();
sis.close();
}
}