一、File类:
1、java.io下的File类
(1)、凡是与输入、输出相关的类、接口等都定义在java.io包下。
(2)、File是一个类,可以有构造器创建其对象。此对象对应着一个文件(.txt, .avi, .doc, .ppt, .mp3, .jpg)等等。
(3)、File类对象是与平台无关的。
(4)、File中的对象,仅仅涉及到如何创建、删除、重命名等等;只要涉及文件内容的如:修改、读取等,做不了,需要IO流来完成。
(5)、File类的对象常作为IO流的具体类的构造器的形参。
2、
(1)、File类的使用格式:File file=new File(字符串类型的路径);
(2)、路径:
绝对路径:包含盘符在内的完整的文件路径
相对路径:相对于当前文件目录的文件路径
(3)、File file=new File("d:\\io\\helloworld.txt"); //正常情况下路径为:"d:\io\helloworld.txt";但此处因为是java语句,具有跨平台性,所以应该加双斜线或者是一个方向相反的斜线。
代码实例:
package com.atguigu.File;
import java.io.File;
import org.junit.Test;
/*
* java.io下的File类
* 1、凡是与输入、输出相关的类、接口等都定义在java.io包下。
* 2、File是一个类,可以有构造器创建其对象。此对象对应着一个文件( .txt, .avi, .doc, .ppt, .mp3, .jpg)或
* 3、File类对象是与平台无关的。
* 4、File中的对象,仅仅涉及到如何创建、删除、重命名等等;只要涉及文件内容的如:修改、读取等,做不了,需要IO流来完成。
* 5、File类的对象常作为IO流的具体类的构造器的形参。
* */
public class TestFile {
/*
* 路径
* 绝对路径:包含盘符在内的完整的文件路径
* 相对路径:相对于当前文件目录的文件路径
* */
@Test
public void test1() {
File file=new File("d:\\io\\helloworld.txt");//正常情况下路径为:"d:\io\helloworld.txt";但此处因为是java语句,具有跨平台性,所以应该加双斜线或者是一个方向相反的斜线。
File file2=new File("hello.txt"); //同级目录下的路径
}
}
二、File类的使用:
File类的方法:
package com.atguigu.File;
import java.io.File;
import java.io.IOException;
import java.util.Date;
import org.junit.Test;
/*
* java.io下的File类
* 1、凡是与输入、输出相关的类、接口等都定义在java.io包下。
* 2、File是一个类,可以有构造器创建其对象。此对象对应着一个文件( .txt, .avi, .doc, .ppt, .mp3, .jpg)或
* 3、File类对象是与平台无关的。
* 4、File中的对象,仅仅涉及到如何创建、删除、重命名等等;只要涉及文件内容的如:修改、读取等,做不了,需要IO流来完成。
* 5、File类的对象常作为IO流的具体类的构造器的形参。
* */
public class TestFile {
/*
* createNewFile
* delete()
* mkDir():创建一个文件目录。只有在上层文件目录存在的情况下才能返回true。
* mkDirs():创建一个文件目录。若上层文件目录不存在,一并创建。
* list()
* listFiles()
*
* */
@Test
public void test3() throws IOException {
File file1=new File("d:/io/hello.txt");
System.out.println(file1.delete());
if(!file1.exists()) { //判断是否存在,不存在则创建
boolean b=file1.createNewFile();//创建文件中的文档
System.out.println(b);
}
File file2=new File("d:\\io2\\io3\\io5");
if(!file2.exists()) {
System.out.println(file2.mkdir()); //创建文件目录
}
File file3=new File("d:\\teach");//将teach中的所有内容遍历出来。
String[] strs=file3.list();
for(int i=0;i<strs.length;i++) {
System.out.println(strs[i]);
}
File[] files=file3.listFiles(); //只遍历文件名
for(int i=0;i<files.length;i++) {
System.out.println(files[i].getName());
}
}
@Test
public void test2() {
File file1=new File("d:/io/hello.txt");
File file2=new File("hello1.txt");
File file3=new File("d:\\io\\io1");
File file4=new File("d:\\ios");
System.out.println(file1.exists());
System.out.println(file1.canWrite());
System.out.println(file1.canRead());
System.out.println(file1.isFile());
System.out.println(file1.isDirectory());
System.out.println(file1.lastModified());//本来显示的全是毫秒数,加一个new Date()后就可以显示很好看的时间。
System.out.println(file1.length());
}
/*
* 路径
* 绝对路径:包含盘符在内的完整的文件路径
* 相对路径:相对于当前文件目录的文件路径
* */
@Test
public void test1() {
File file1=new File("d:/io/helloworld.txt");//hu'e'dui'lu'jin'h //正常情况下路径为:"d:\io\helloworld.txt";但此处因为是java语句,具有跨平台性,所以应该加双斜线或者是一个方向相反的斜线。
File file2=new File("hello.txt"); //同级目录下的路径
File file3=new File("d:\\io\\io1"); //文件
File file4=new File("d:\\io2");
System.out.println(file1.getName()); //获取文件的名
System.out.println(file1.getPath()); //获取文件路径
System.out.println(file1.getAbsolutePath()); //获取绝对路径
System.out.println(file1.getAbsoluteFile()); //获取绝对文件名
System.out.println(file1.getParent()); //父文件路径
System.out.println("**************************");
System.out.println(file3.getName()); //获取文件的名
System.out.println(file3.getPath()); //获取文件路径
System.out.println(file3.getAbsolutePath()); //获取绝对路径
System.out.println(file3.getAbsoluteFile()); //获取绝对文件名
System.out.println(file3.getParent()); //父文件路径
//renameTo(File newName):返回boolean类型
//file1.renameTo(file2):file重命名为file2,要求:file1文件一定存在,file2一定不存在。
// boolean b=file1.renameTo(file2);
// System.out.println(b);
boolean b1=file4.renameTo(file3);
System.out.println(b1);
}
}
三、IO流的概述:
四、IO流的使用(FileInputStream、FileOutputStream):
(1)、定义一个File类的对象;
(2)、定义一个写入流对象和一个读出流对象;
(3)、File类对象写进流中;
(4)、从写入的对象中把数据写进另一个流。
在Input里读(read),往Output里写(write)。
FileReader与FileWriter实现复制与下方相同类似。
复制4步走:
//实现文件的复制的方法
public void copyFile(String src,String dest) {
//1、提供读入、写出的文件
// File file1=new File("hello.txt");
// File file3=new File("hello5.txt");
File file1=new File(src);
File file3=new File(dest);
//2、提供相应的流
FileInputStream fis=null;
FileOutputStream fos=null;
try {
fis=new FileInputStream(file1); //输入到程序里
fos=new FileOutputStream(file3); //输出并保存到文件中
//3、实现文件的复制
byte[] b=new byte[1024];
int len;
while((len=fis.read(b))!=-1) { //读出对应fis(输入流的输入到程序里)
// fos.write(b); 错误的写法 fos.write(b,0,b.length);
fos.write(b,0,len); //写入文件
}
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}finally {
//4、关闭文件流
if(fos!=null) {
try {
fos.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
try {
fis.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
输入流对应的文件一定要存在,输出流对应的文件可以不存在,后期会自动创建。
FileInputStream与FileOutputStream都是字节流byte[ ]:用于非文本文件(视频文件、音频文件、图片),只能使用字节流;而FileReader、FileWriter都是字符流char[ ],可以实现文本文件的复制。
1、FileInputStream的读取文件的操作:(输入的是输入到程序里,需要读(read)一下;输出的是输出到文件里,需要写(write)一下,写进文件里)
package com.atguigu.File;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import org.junit.Test;
/*
* 1、流的分类:
* 按照数据流向的不同:输入流输出流
* 按照处理数据的单位的不同:字节流、字符流(处理的文本文件)
* 按照角色的不同:节点流(直接作用于文件的)、 处理流
* 2、IO的体系
* 抽象基类:类 节点流(文件流):类
*InputStream FileInputStream
*OutputStream FileoutputStream
*Reader FileReader
*Writer FileWriter
*
*
* 重难点:数组的 */
public class TestFileInputOutputStream {
@Test
public void testFileInputOutputStream3(){
FileInputStream fis=null;
try {
File file1=new File("hello.txt");
fis = new FileInputStream(file1);
byte[] b=new byte[5];//定义了一个数组,数组用于存读取到的数据。
int len;//每次读入到byte中的字节的长度。
while((len=fis.read(b))!=-1) {
// 方式一: for(int i=0;i<len;i++) {
// System.out.println((char)b[i]);
// }
// 方式二:
String str=new String(b, 0, len);
System.out.println(str);
}
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally {
if(fis!=null) {
try {
fis.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
@Test/********使用try-catch抛出异常会比较好,可以保证流的关闭操作一定可以执行*********/
public void testFileInputStream2(){
//2、创建FileInputStream类的对象
FileInputStream fis=null;
try {
//1、创建File类的对象
@SuppressWarnings("unused")
File file1=new File("hello.txt");
fis = new FileInputStream(file1);
//3、用FileInputStream的reader方法
/*
* reader():读取文件的一个字节。执行到文件结尾时返回空
* */
int n;
while((n=fis.read())!=-1) {
System.out.print((char)n);
}
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
//4、关闭相应的流,内存的资源在用完后可以回收;但是流的资源不可以,必须显式的回收。
finally{
try { //再try-catch一次
fis.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
//从硬盘存在的一个文件中,读取其内容到程序中。使用FileInputStream
//要读取的文件一定要存在,否则会抛出FileNotFoundException异常。
@Test
public void testFileInputStream1() throws IOException {
//1、创建File类的对象
@SuppressWarnings("unused")
File file1=new File("hello.txt");
//2、创建FileInputStream类的对象
FileInputStream fis=new FileInputStream(file1);//需要抛出异常
int n=fis.read();
//3、用FileInputStream的reader方法
/*
* reader():读取文件的一个字节。执行到文件结尾时返回空
* */
while(n!=-1) {
System.out.print((char)n);
n=fis.read();
}
//4、关闭相应的流,内存的资源在用完后可以回收;但是流的资源不可以,必须显式的回收。
fis.close();
}
}
2、FileOutputStream的文件复制操作:
package com.atguigu.File;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import org.junit.Test;
/*
* 1、流的分类:
* 按照数据流向的不同:输入流输出流
* 按照处理数据的单位的不同:字节流、字符流(处理的文本文件)
* 按照角色的不同:节点流(直接作用于文件的)、 处理流
* 2、IO的体系
* 抽象基类:类 节点流(文件流):类
*InputStream FileInputStream
*OutputStream FileoutputStream
*Reader FileReader
*Writer FileWriter
*
*
* */
public class TestFileInputOutputStream {
@Test
public void testCopyFile() {
long start=System.currentTimeMillis();
String src="C:\\Users\\yts\\Desktop\\1.png";
String dest="D:\\5.jpg";
copyFile(src, dest);
long end=System.currentTimeMillis();
System.out.println("花费时间为:"+(end-start));
}
//实现文件的复制的方法
public void copyFile(String src,String dest) {
//1、提供读入、写出的文件
// File file1=new File("hello.txt");
// File file3=new File("hello5.txt");
File file1=new File(src);
File file3=new File(dest);
//2、提供相应的流
FileInputStream fis=null;
FileOutputStream fos=null;
try { //文件放入输入、输出流中
fis=new FileInputStream(file1);
fos=new FileOutputStream(file3);
//实现文件的复制
byte[] b=new byte[1024];
int len;
while((len=fis.read(b))!=-1) { //从程序中把数据读出
// fos.write(b); 错误的写法 fos.write(吧,0,b.length);
fos.write(b,0,len); //读出的数据写入文件目标中
}
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}finally {//4、关闭文件流
if(fos!=null) {
try {
fos.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
try {
fis.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
/*
* 从硬盘读取一个文件并写入到另一个位置。(相当于文件的复制)
* 如果写出到的文本不存在会自动创建一个,存在于盘中,即使开关机之后也不会消失
* */
@Test
public void testInOutputStream() {
//1、提供读入、写出的文件
// File file1=new File("hello.txt");
// File file3=new File("hello5.txt");
File file1=new File("C:\\Users\\yts\\Desktop\\1.png");
File file3=new File("C:\\Users\\yts\\Desktop\\2.png");
//2、提供相应的流
FileInputStream fis=null;
FileOutputStream fos=null;
try {
//代表从file1中把数据写进新的file2中
fis=new FileInputStream(file1);
fos=new FileOutputStream(file3);
//实现文件的复制
byte[] b=new byte[20];
int len;
while((len=fis.read(b))!=-1) {
// fos.write(b); 错误的写法 fos.write(吧,0,b.length);
fos.write(b,0,len);
}
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}finally {//4、关闭文件流
if(fos!=null) {
try {
fos.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
try {
fis.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
//FileOutputStream
@Test
public void testOutputstream() {
//1、创建一个File对象,表明要写入的文件位置
//如果不存在"hello2.txt"的物理文件,会自动创建此文件用于写出。
File file1=new File("hello2.txt");
//2、创建一个FileoutputStream对象,将File的对象作为形参传递给FileOutputStream的构造中
FileOutputStream fos=null;
try {
fos=new FileOutputStream(file1);
//3、写入的操作
fos.write(new String("I love you").getBytes());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally {
//4、关闭输出流
if(fos!=null) {
try {
fos.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
}
3、FileReader与FileWriter的使用代码实例:
输入流对应的文件一定要存在,输出流对应的文件可以不存在,后期会自动创建。
FileInputStream与FileOutputStream都是字节流byte[ ]:用于非文本文件(视频文件、音频文件、图片),只能使用字节流;而FileReader、FileWriter都是字符流char[ ],可以实现文本文件的复制。
package com.atguigu.File;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import org.junit.Test;
/*
* FileReader和FileWriter都是字符char型的数据存的。
* */
public class TestFileReaderWriter {
@Test
public void FileReaderWriter() {
//1、输入流(Input)对应的文件src一定要存在,否则异常;输出流(Output)对应的文件dest可以不存在,执行过程中会自动创建。
FileReader fr=null;
FileWriter fw=null;
try {
File src=new File("dbcp.txt");//"dbcp.txt"再java project项目上右击--new--File--......
File dest=new File("dbcp1.txt");
//2、从src中读,写进dest中
fr=new FileReader(src);
fw=new FileWriter(dest);
//3、
char[] c=new char[24];
int len;
while((len=fr.read(c))!=-1) {
fw.write(c,0,len);
}
}catch(Exception e) {
e.printStackTrace();
}finally {
if(fw!=null) {
try {
fw.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if(fr!=null) {
try {
fr.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
@Test
public void testFileReader(){
FileReader fr=null;
try {
File file=new File("dbcp.txt");
fr=new FileReader(file);
char[] c=new char[24];
int len;
while((len=fr.read(c))!=-1) {
String str=new String(c,0,len);
System.out.println(str);
}
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally {
if(fr!=null) {
try {
fr.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
}
除了以上四个节点流(文件流)之外,其他都是缓冲流。
五、缓冲流的使用:(Buffered在实现复制时需通过中介-FileInputStream、FileReader等等)
开发时不用之前的四个File什么什么;而用现在的Buffered什么什么,因为Buffered什么什么效率更高。
缓冲流可以提升文件操作的效率。
FileInputStream等是阻塞式的,即你不告诉我后边还有没有我就一直等待;
package com.atguigu.File;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import org.junit.Test;
/*
* 2、IO的体系
* 抽象基类:类 节点流(文件流):类 缓冲流(处理流的一种):类
*InputStream FileInputStream (byte型数组) BufferInputStream
*OutputStream FileoutputStream(byte型数组) BufferOutputStream (加"对象.flush();")
*Reader FileReader(char型数组) BufferReader (也可以用char型数组,还有readLine方法)
*Writer FileWriter(char型数组) BufferWriter (加"对象.flush();")
*
*/
public class TestBuffer {
@Test
public void testBuffered1() {
BufferedReader br=null;
BufferedWriter bw=null;
try {
File file=new File("dbcp.txt");
File file1=new File("db.txt");
//与之前的相比,多了下面的两个语句
FileReader fr=new FileReader(file);
FileWriter fw=new FileWriter(file1);
br=new BufferedReader(fr);
bw=new BufferedWriter(fw);
// char[] c=new char[1024];
// int len;
// while((len=br.read(c))!=-1) {
// String str=new String(c,0,len);
// System.out.println(str);
// }
String str=null;
while((str=br.readLine())!=null) {//读
// System.out.println(str);
bw.write(str);//写
bw.newLine();//自动换行
bw.flush();
}
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally {
if(br!=null) {
try {
br.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
@Test
public void testBuffered() {
BufferedReader br=null;
try {
File file=new File("dbcp.txt");
FileReader fr=new FileReader(file);
br=new BufferedReader(fr);
// char[] c=new char[1024];
// int len;
// while((len=br.read(c))!=-1) {
// String str=new String(c,0,len);
// System.out.println(str);
// }
String str=null;
while((str=br.readLine())!=null) {
System.out.println(str);
}
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally {
if(br!=null) {
try {
br.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
//测试复制的正确性
@Test
public void testCopyFile() {
//花费的时间
long start=System.currentTimeMillis();
String src="C:\\Users\\yts\\Desktop\\1.png";
String dest="D:\\45.jpg";
copyFile(src, dest);
long end=System.currentTimeMillis();
System.out.println("费时:"+(end-start));
}
//使用缓冲流实现文件的复制的方法
public void copyFile(String src,String dest){
//3、将创建的节点流的对象作为形参传递给缓冲流的构造器中
BufferedInputStream bis=null;
BufferedOutputStream bos=null;
try {
//1、提供读入、写出的文件
File file1=new File(src);
File file2=new File(dest);
//2、想创建相应的节点流,FileInputStream、FileOutputStream
FileInputStream fis=new FileInputStream(file1);
FileOutputStream fos=new FileOutputStream(file2);
bis=new BufferedInputStream(fis);
bos=new BufferedOutputStream(fos);
//4、具体的实现文件复制的操作
byte[] b=new byte[1024];
int len;
while((len=bis.read(b))!=-1) {
bos.write(b,0,len);
bos.flush();
}
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally {
//5、关闭文件
if(bos!=null) {
try {
bos.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if(bis!=null) {
try {
bis.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
}
六、缓冲流的使用:(转换流)
解码:字节数组à字符串:看不懂的转换为可以看得懂的。
编码:字符串à字节数组:看得懂的转换为看不懂的。
转换流:(1)、InputStreamReader流:相当于是在解码;(2)、OutputStreamWriter流:相当于是在编码。
package com.atguigu.File;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;
import org.junit.Test;
public class TestOtherStream {
/*
* 标准的输入输出流:
* 标准的输出流(输出到显示器):System.out
* 标准的输入流(从键盘输入到屏幕):System.in
*
* 题目:
* 从键盘输入字符串,要求将读取到的整行字符串转成大写输出。然后继续进行输入操作。
* 直至当输入"e"或者"exit"时,退出程序。
* */
@Test
public void test2() {
BufferedReader br = null;
try {
InputStream is=System.in;
InputStreamReader isr=new InputStreamReader(is);
br = new BufferedReader(isr);
String str;
while(true) {
System.out.println("请输入字符串");
str=br.readLine();
if(str.equalsIgnoreCase("e") || str.equalsIgnoreCase("exit")) {
break;
}
String str1=str.toUpperCase();
System.out.println(str1);
}
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
try {
if(br!=null) { //如果不将br赋值为null的话此处的br会出错。
br.close();
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
/*
* 转换流:InputStreamReader OutputStream
* 编码:字符串----字符数组
* 解码:字符数组----字符串
* */
@Test
public void test1(){
BufferedReader br=null;
BufferedWriter bw=null;
try {
//解码(本身是一个节点流,但是真正处理时是当成一个文本文件)
File file=new File("dbcp.txt");//处理时用文本文件
FileInputStream fis=new FileInputStream(file);//本身是节点流
InputStreamReader isr=new InputStreamReader(fis,"GBK");//存在编码集
br=new BufferedReader(isr);
//编码
File file1=new File("dbcp4.txt");
FileOutputStream fos=new FileOutputStream(file1);
OutputStreamWriter osw=new OutputStreamWriter(fos,"GBK");
bw=new BufferedWriter(osw);
String str;
while((str=br.readLine())!=null) {
bw.write(str);
bw.newLine();
bw.flush();
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally{
if(bw!=null) {
try {
bw.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
}