一:File类
1. File类提供了对当前文件系统中文件的部分操作;
2. 常用API:
1) 创建:
1)file.createNewFile(); 创建文件
2)file.mkdir(); 创建单级文件目录
3)file.mkdirs(); 创建多级文件目录;
2)查询:
1)file.canExecute(); 判断该文件是否可以被执行
2)file.canRead(); 判断该文件是否可以读
3)file.canWrite(); 判断该文件是否能被写入
4)file.exists(); 判断当前文件是否存在
5)file.getName(); 获取文件名称
6)file.getAbsolutePath(); 获取文件绝对路径
7)file.getParent(); 获取当前文件的父路径名称,如果文件的路径只包含文件名称本身,则显示为空
8)file.getCanonicalPath(); 获取文件路径规范格式
9)file.isDirectory(); 判断当前文件是否为文件夹;
10)file.isFile(); 判断当前文件是否为文件;
11)file.list(); 获取文件夹中的文件名称
12)file.listFiles(); 获取文件夹中的文件路径
13)File.listRoots(); 获取当前文件路径的所有盘符
3)代码实现:
public class FileDemo {
public static void main(String[] args) throws IOException {
File file = new File("abc.txt");
//创建文件
try {
file.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
//判断文件属性,都会返回Boolean类型的值
//判断该文件是否可以被执行
file.canExecute();
//判断该文件是否可以读
file.canRead();
//判断该文件是否能被写入
file.canWrite();
//判断当前文件是否存在
System.out.println(file.exists());
//获取文件名称
System.out.println(file.getName());
//获取文件绝对路径,无论文件创建与否,只要给定特定的路径,都可以返回相应的路径名称
System.out.println(file.getAbsolutePath());
//获取当前文件的父路径名称,如果文件的路径只包含文件名称本身,则显示为空
System.out.println(file.getParent());
//获取文件路径规范格式
System.out.println(file.getCanonicalPath());
//获取文件分隔符
System.out.println(File.separator);
//判断当前文件是文件还是目录
System.out.println(file.isDirectory());
System.out.println(file.isFile());
//获取文件夹中的文件名称
File file1 = new File("d:/");
String[] list = file1.list();
for (String str:list) {
System.out.println(str);
}
//获取文件夹中的文件路径
File[] files = file1.listFiles();
for (File f:files ) {
System.out.println(f);
}
//获取当前文件路径的所有盘符
File[] files1 = File.listRoots();
for (int i = 0; i < files1.length; i++) {
System.out.println(files1[i]);
}
//创建单级文件目录
new File("d:/view/").mkdir();
//创建多级文件目录
new File("d:/a/b/c").mkdirs();
//循环遍历指定系统文件加中所有文件的绝对路径
printFile(new File("F:\\StudyCode"));
}
/**
* 打印文件绝对路径
* 注意:文件在遍历时报空指针异常原因是当前文件系统受保护,某些文件没有访问权限
* @param file
*/
public static void printFile(File file){
if(file.isDirectory()){
File[] files = file.listFiles();
for (File f:files) {
printFile(f);
}
}else{
System.out.println(file.getAbsolutePath());
}
}
}
二:流
1.概念: 一连串流动的字符,通过先进先出方式发送信息的通道;
2.分类:
1)按流的方向划分:输入流和输出流;(以程序作为参照物)
a) 输入流: 从文件读取到程序;
b) 输出流:从程序读取到文件;
2) 按处理的数据单位划分:字节流(8bit)和字符流(16bit);
字节流和字符流的区别:
a) 字符流可以直接读取中文汉字,而字节流在处理时会出现中文乱码现象;
b)缓冲区创建对象不同,字符流创建的是char[],字节流创建的是byte[];
c) 在处理图片、视频时使用字节流,处理纯文本时用字符流;
3) 按功能划分:节点流和处理流;
节点流:可以直接从数据源或目的地读写数据;
处理流(包装流):不直接连接到数据源或目的地,是对其他流进行包装,目的主要是简化操作和提高性能。(字节流转化字符流的桥梁)
三:字节流和字符流读写操作
package com.cy.write;
import java.io.*;
public class CopyImg {
public static void main(String[] args) {
File file =new File("F:\\test.jpg");
//字符流复制
charStream(file);
//字节流复制
//byteStream(file);
}
/**
* 字节流复制图片
*/
private static void byteStream(File file) {
InputStream inputStream=null;
OutputStream outputStream=null;
try {
inputStream=new FileInputStream(file);
outputStream=new FileOutputStream("test03.jpg");
//创建缓冲区
byte[] buffer=new byte[1024];
int length=0;
while ((length=inputStream.read(buffer))!=-1){
outputStream.write(buffer);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}finally {
try {
inputStream.close();
outputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
/**
* 字符流复制图片
*/
private static void charStream(File file) {
Reader reader=null;
Writer writer=null;
try {
reader= new FileReader(file);
writer= new FileWriter("test1.jpg");
//创建缓冲区
char[] chars= new char[1024];
int length=0;
while ((length=reader.read(chars))!=-1){
writer.write(chars);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}finally {
try {
reader.close();
writer.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
四:节点流和处理流 :
1.节点流:
1)文件:FileInPutStream、FileOutputStream、FileReader、FileWriter
package com.cy.stream;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
/**
* 在java中需要读写文件中的数据时,需要使用流的概念:
* 流表示从一个文件传输数据到另一个文件,包含一个流向问题:
* 注意:在编写IO程序时,一定要注意关闭流
* 步骤:1.选择合适的IO流对象;
* 2.创建对象;
* 3.传输数据;
* 4.关闭流对象(会占用系统资源);
*
*/
public class InputStreamDemo2 {
public static void main(String[] args) {
InputStream inputStream=null;
//创建对象
try {
inputStream=new FileInputStream("abc.txt");
//循环输出所有字节
int length=0;
//添加缓冲区的方式进行读取,每次会将数据添加到缓冲区中,当缓冲区满了之后,进行一次读取,而不是一个个字节进行读取;
byte[] buffer=new byte[1024];
while ((length=inputStream.read(buffer,5,5))!=-1){
System.out.println(new String(buffer,5,length));
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}finally {
try {
inputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
package com.cy.stream;
import java.io.*;
import java.nio.charset.StandardCharsets;
public class OutPutStreamDemo {
public static void main(String[] args) {
File file = new File("text.txt");
OutputStream outputStream=null;
try {
outputStream=new FileOutputStream(file);
outputStream.write(99);
outputStream.write("\\r\\n学习IO".getBytes(StandardCharsets.UTF_8));
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}finally {
try {
outputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
package com.cy.reader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.Reader;
public class ReaderDemo3 {
public static void main(String[] args) {
Reader reader = null;
try {
reader = new FileReader("abc.txt");
int length=0;
char[] chars=new char[1024];
//添加缓冲区
while ((length=reader.read(chars))!=-1){
System.out.print(new String(chars,0,length));
}
// int read = reader.read();
// System.out.println((char) read);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}finally {
try {
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
package com.cy.write;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.Writer;
/**
* 什么时候加flush?
* 最保险的方式:在输出流关闭时,每次都flush;
* 当某一个流对象带有缓冲区的时候,就需要进行flush;
*/
public class WirteDemo {
public static void main(String[] args) {
File file = new File("write.txt");
Writer writer=null;
try {
writer=new FileWriter(file);
writer.write("abc");
writer.write("隔壁老王");
} catch (IOException e) {
e.printStackTrace();
}finally {
try {
writer.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
2) 数组: ByteArrayInputStream、ByteArrayOutputStream
CharArrayReader、 CharArrayWriter 对数组进行处理的节点流(对应的不再是文件,而是内存中的一个数组)。
package com.cy.stream.type;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
/**
* 字节数组转字节流--读
*/
public class ByteArrayInputStreamDeamo {
public static void main(String[] args) {
String str="abcdefg";
byte[] buffer = str.getBytes(StandardCharsets.UTF_8);
ByteArrayInputStream byteArrayInputStream=null;
byteArrayInputStream=new ByteArrayInputStream(buffer);
int read=0;
while ((read=byteArrayInputStream.read())!=-1){
//跳读
byteArrayInputStream.skip(4);
System.out.println((char)read);
}
try {
byteArrayInputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
package com.cy.stream.type;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
/**
* 字节数组转字节流--写
*/
public class ByteArrayOutPutStreamDemo {
public static void main(String[] args) {
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
byteArrayOutputStream.write(123);
try {
byteArrayOutputStream.write("abcdefg".getBytes(StandardCharsets.UTF_8));
System.out.println(byteArrayOutputStream.toString());
} catch (IOException e) {
e.printStackTrace();
}finally {
try {
byteArrayOutputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
package com.cy.stream.type;
import java.io.CharArrayReader;
import java.io.IOException;
/**
* char数组转字符流--读
*/
public class CharArrayReaderDemo {
public static void main(String[] args) {
String str="编程小子";
char[] chars = str.toCharArray();
CharArrayReader charArrayReader = new CharArrayReader(chars);
try {
int read =0;
while((read=charArrayReader.read())!=-1){
System.out.print((char) read);
}
} catch (IOException e) {
e.printStackTrace();
}finally {
charArrayReader.close();
}
}
}
package com.cy.stream.type;
import java.io.CharArrayWriter;
/**
* char数组转字符流--写
*/
public class CharArrayWriterDemo {
public static void main(String[] args) {
CharArrayWriter charArrayWriter = new CharArrayWriter();
charArrayWriter.write(97);
charArrayWriter.write(98);
charArrayWriter.write(99);
System.out.println(charArrayWriter);
charArrayWriter.close();
}
}
2.处理流:
1)缓冲流:BufferedInputStrean、 BufferedOutputStream、 BufferedReader、 BufferedWriter增加缓冲功能,避免频繁读写硬盘。
package com.cy.stream.type;
import java.io.*;
/**
* 处理流--缓冲区流(读)
*
*/
public class BufferedInputStreamDemo {
public static void main(String[] args) {
File file = new File("abc.txt");
FileInputStream fileInputStream=null;
BufferedInputStream bufferedInputStream=null;
try {
fileInputStream = new FileInputStream(file);
bufferedInputStream = new BufferedInputStream(fileInputStream);
int read=0;
while ((read=bufferedInputStream.read())!=-1){
bufferedInputStream.skip(10);
System.out.print((char)read);
}
} catch (FileNotFoundException e) {
} catch (IOException e) {
e.printStackTrace();
}finally {
try {
bufferedInputStream.close();
fileInputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
package com.cy.stream.type;
import java.io.*;
import java.nio.charset.StandardCharsets;
/**
* 处理流--缓冲区(写)
*/
public class BufferedOutPutStreamDemo {
public static void main(String[] args) {
File file = new File("text.txt");
FileOutputStream fileOutputStream=null;
BufferedOutputStream bufferedOutputStream=null;
try {
fileOutputStream = new FileOutputStream(file);
bufferedOutputStream = new BufferedOutputStream(fileOutputStream);
bufferedOutputStream.write(98);
bufferedOutputStream.write("www.baidu.com".getBytes(StandardCharsets.UTF_8));
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}finally {
try {
bufferedOutputStream.close();
fileOutputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
package com.cy.stream.type;
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
/**
* 字符流缓冲区
* 每次读取到一整行记录
*/
public class BufferedReadDemo {
public static void main(String[] args) {
BufferedReader reader=null;
try {
reader=new BufferedReader(new FileReader("write.txt"));
String str = null;
while ((str=reader.readLine())!=null){
System.out.println(str);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
package com.cy.stream.type;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
/**
* 字符缓冲流--写
*/
public class BufferedWriterDemo {
public static void main(String[] args) {
FileWriter fileWriter = null;
BufferedWriter bufferedWriter=null;
try {
fileWriter = new FileWriter(new File("abc.txt"));
bufferedWriter = new BufferedWriter(fileWriter);
bufferedWriter.write("编程小子");
bufferedWriter.append("最帅");
bufferedWriter.newLine();
bufferedWriter.write("hfjofhii");
bufferedWriter.flush();
} catch (IOException e) {
e.printStackTrace();
}finally {
try {
bufferedWriter.close();
fileWriter.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
2)转换流:InputStreamReader、OutputStreamReader实现字节流和字符流之间的转换。
package com.cy.handlerStream;
import java.io.*;
/**
* 处理流--读
*/
public class InPutStreamReaderDemo {
public static void main(String[] args) {
File file = new File("abc.txt");
FileInputStream fileInputStream=null;
InputStreamReader inputStreamReader=null;
try {
fileInputStream = new FileInputStream(file);
inputStreamReader= new InputStreamReader(fileInputStream,"utf8");
//创建缓冲区
char[] chars=new char[1024];
int length = inputStreamReader.read(chars);
System.out.println(new String(chars,0,length));
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
fileInputStream.close();
inputStreamReader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
package com.cy.handlerStream;
import java.io.*;
/**
* 处理流--写
*/
public class OutPutStreamWriteDemo {
public static void main(String[] args) {
File file = new File("abc.txt");
FileOutputStream fileOutputStream=null;
OutputStreamWriter outputStreamWriter=null;
try {
long start=System.currentTimeMillis();
fileOutputStream= new FileOutputStream(file);
outputStreamWriter= new OutputStreamWriter(fileOutputStream,"utf-8");
outputStreamWriter.write("隔壁老王");
outputStreamWriter.write("abcdefg",0,5);
long end=System.currentTimeMillis();
System.out.println(end-start);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}finally {
try {
outputStreamWriter.close();
fileOutputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
3)数据流 DataInputStream、 DataOutputStream、ObjectInputStream、ObjectOutputStream 等-提供将基础数据类型写入到文件中,或者读取出来.
package com.cy.stream.type;
import java.io.*;
/**
* 装饰流(读写操作)
*/
public class DataStreamDemo {
public static void main(String[] args) {
FileInputStream fileInputStream = null;
FileOutputStream fileOutputStream = null;
DataInputStream dataInputStream = null;
DataOutputStream dataOutputStream = null;
try {
fileInputStream = new FileInputStream("abc.txt");
fileOutputStream = new FileOutputStream("abc.txt");
dataInputStream =new DataInputStream(fileInputStream);
dataOutputStream = new DataOutputStream(fileOutputStream);
//向文件中写入数据流
dataOutputStream.writeBoolean(true);
dataOutputStream.writeDouble(3.1415926);
dataOutputStream.writeFloat(2.0f);
dataOutputStream.writeShort(500);
dataOutputStream.writeUTF("www.baidu.com百度");
//向文件中读取数据流
System.out.println(dataInputStream.readBoolean());
System.out.println(dataInputStream.readDouble());
System.out.println(dataInputStream.readFloat());
System.out.println(dataInputStream.readShort());
System.out.println(dataInputStream.readUTF());
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}finally {
try {
fileInputStream.close();
fileOutputStream.close();
dataOutputStream.close();
dataInputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
package com.cy.stream.type;
import com.cy.pojo.Person;
import java.io.*;
/**
* 读取对象流
*/
public class ObjectInPutStreamDemo {
public static void main(String[] args) {
FileInputStream fileInputStream = null;
ObjectInputStream objectInputStream=null;
try {
fileInputStream=new FileInputStream("abc.txt");
objectInputStream=new ObjectInputStream(fileInputStream);
System.out.println(objectInputStream.readUTF());
Person person =(Person) objectInputStream.readObject();
System.out.println(person);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
} finally {
try {
fileInputStream.close();
objectInputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
package com.cy.stream.type;
import com.cy.pojo.Person;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectOutputStream;
/**
* 保存序列化对象流
*/
public class ObjectOutPutStreamDemo {
public static void main(String[] args) {
FileOutputStream fileOutputStream=null;
ObjectOutputStream objectOutputStream=null;
try {
fileOutputStream=new FileOutputStream("abc.txt");
objectOutputStream = new ObjectOutputStream(fileOutputStream);
objectOutputStream.writeUTF("www.baidu.com");
objectOutputStream.writeObject(new Person(1,"老王",19));
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}finally {
try {
fileOutputStream.close();
objectOutputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
五:扩展
1.标准输入、标准输出、打印流:
标准输入:System.in;
标准输出:System.out;
练习:实现命令行读取输入输出功能
package com.cy.project;
import java.io.*;
/**
* 练习标准输入、输出
* 命令行读取输入输出
*/
public class ExitTest {
public static void main(String[] args) {
try(//字节流字符流过渡桥梁
//默认关闭流
InputStreamReader inputStreamReader = new InputStreamReader(System.in);
OutputStreamWriter outputStreamWriter = new OutputStreamWriter(System.out);
BufferedReader reader = new BufferedReader(inputStreamReader);
BufferedWriter writer = new BufferedWriter(outputStreamWriter);) {
String str = "";
while (!str.equals("exit")) {
str = reader.readLine();
writer.write(str);
writer.flush();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
2.打印流PrintStream
package com.cy.stream.type;
import java.io.IOException;
import java.io.PrintStream;
import java.nio.charset.StandardCharsets;
/**
* 打印流
*/
public class PrintStreamDemo {
public static void main(String[] args) {
PrintStream printStream = new PrintStream(System.out);
try {
printStream.write("编程小子".getBytes(StandardCharsets.UTF_8));
printStream.print(true);
System.out.println("编程小子"+true);
//格式化输出 %s:字符串 %d:整数 %f: 浮点数
System.out.printf("%s--%d--%.2f","abc",520,3.1415926);
//错误输出
System.err.println("laownab");
} catch (IOException e) {
e.printStackTrace();
} finally {
printStream.close();
}
}
}
3.RandomAccessFile
package com;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.RandomAccessFile;
/**
* 分块读取文件
*/
public class RandomAccessFileDemo {
public static void main(String[] args) {
File file = new File("dsc.txt");
//整个文件的大小
long length = file.length();
//规定块的大小
int blockSize=1024;
//文件可以被切割成多少块
int size=(int)(length*1.0/blockSize);
//格式化输出
System.out.printf("要被切割成<%d>个块",size);
//起始偏移量
int beginPos=0;
//实际长度
int actualSize=(int)(blockSize>length? length: blockSize);
for (int i = 0; i <size ; i++) {
//每次读取时的偏移量
beginPos=i*blockSize;
if (i==size-1){
actualSize=(int) length;
}else{
actualSize=blockSize;
length-=actualSize;
}
System.out.println(i+"---->起始位置是:"+beginPos+"----读取的大小是"+actualSize);
readspilt(i,beginPos,actualSize);
}
}
/**
* 分块读取方法
* @param i
* @param baginPos
* @param actualSize
*/
public static void readspilt(int i,int baginPos,int actualSize){
RandomAccessFile randomAccessFile=null;
try {
randomAccessFile=new RandomAccessFile(new File("dsc.txt"),"r");
//表示从那个偏移量开始读取数据
randomAccessFile.seek(baginPos);
//创建缓冲区数组
byte[] bytes=new byte[1024];
int length=0;
while ((length=randomAccessFile.read(bytes))!=-1){
//实际长度大于剩余长度
if (actualSize>length){
System.out.println(new String(bytes,0,length));
length-=actualSize;
}else{
System.out.println(new String(bytes,0,actualSize));
break;
}
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}finally {
try {
randomAccessFile.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}