文件的一些基本操作
文件
1、什么是文件?
我们保存数据的地方
2、文件流
文件在程序中以流的形式来操作的
流:数据在数据源(文件)和程序(内存)的路径
输入流:文件到内存的路径
输出流:内存到文件的路径
3、常用的文件操作
1)创建文件对象相关的构造方法
①new File(String pathname)//根据路径构建一个File对象
@Test
public void createFile1(){
String filepath="d:\\file1.txt";
File file=new File(filepath);
try {
file.createNewFile();
System.out.println("文件一创建成功");
} catch (IOException e) {
throw new RuntimeException(e);
}
}
②new File (File parent,String child)//根据父目录文件+子路径构建
@Test
public void create2(){
File parentFile=new File("D:\\");
String fileName="file2.txt";
File file=new File(parentFile,fileName);
try {
file.createNewFile();
System.out.println("文件二创建成功");
} catch (IOException e) {
throw new RuntimeException(e);
}
}
③new File(String parent,String child)//根据父目录+子路径构建
@Test
public void create3(){
String parentPath="d:\\";
String filePath="file3.txt";
File file = new File(parentPath,filePath);
try {
file.createNewFile();
System.out.println("文件三创建成功");//输出流 println 输出换行, print 输出不换行。
} catch (IOException e) {
throw new RuntimeException(e);
}
}
2)获取文件的信息
常见的File相关方法
getName()/getAbsoutePpath()/getParent/length/exists/isFile/isDirectory
//获取文件信息
@Test
public void Info(){
//先创建文件
String filepath="d:\\file1.txt";
File file=new File(filepath);
try {
file.createNewFile();
//System.out.println("文件一创建成功");
} catch (IOException e) {
throw new RuntimeException(e);
}
//调用相应方法,得到对应信息
System.out.println("文件名称:"+ file.getName());
System.out.println("文件绝对路径:"+file.getAbsolutePath());
System.out.println("文件父目录:"+file.getPath());
System.out.println("文件大小(字节):"+file.length());
System.out.println("文件是否存在:"+file.exists());
System.out.println("是否是文件:"+file.isFile());
System.out.println("是否是目录:"+file.isDirectory());
}
3)目录的操作
创建一级目录:mkdir 创建多级目录:mkdirs delete删除空目录或者文件
目录的操作
package FileCreate;
import org.testng.annotations.Test;
import java.io.File;
import java.io.IOException;
public class fileDirectory {
public static void main(String[] args) {
}
@Test
//删除文件
public void fileDelete() {
String filePath = "D:\\file1.txt";
File file = new File(filePath);
try {
file.createNewFile();
} catch (IOException e) {
throw new RuntimeException(e);
}
if (file.exists()) {
if (file.delete()) {
System.out.println("文件删除成功");
} else {
System.out.println("文件删除失败");
};
} else {
System.out.println("文件不存在");
}
}
//删除目录
@Test
public void fileDeleteD(){
String filePath="D:\\file1.txt";
File file = new File(filePath);
if (file.exists()) {
if (file.delete()) {
System.out.println("删除成功");
} else {
System.out.println("删除失败");
};
} else {
System.out.println("目录不存在");
}
}
//判断目录是否存在,不存在就创建
@Test
public void fileDeleteD1(){
String dirPath="D:\\test\\dir1.txt";
File file=new File(dirPath );
if (file.exists()) {
System.out.println(dirPath + "该目录已经存在");
} else {
if (file.mkdirs()) {
System.out.println("创建成功");
} else {
System.out.println("创建失败");
};
}
}
}
4、IO流原理及流的分类
1)input/output,数据写入写出的过程
java中用“流(stream)”来抽象表示这么一个写入写出的功能,封装成一个“类”,都放在java.io这个包里面
2)
字节流 | 字符流 | |
输入流 | InputStream | Reader |
输出流 | OutoutDtream | Writer |
5、IntputStream
常见子类
文件输入流 | 缓冲字节流 | 对象字节输入流 |
FileInputStream | BufferedStream | ObjectedStream |
查看代码
package FileCreate;
import org.testng.annotations.Test;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
public class fileInputStream {
public static void main(String[] args) {
}
@Test
public void fileIn1() {
//String filePath = "D:\\fileinput.txt";
String filepath="d:\\file1.txt";
File file=new File(filepath);
try {
file.createNewFile();
//System.out.println("文件一创建成功");
} catch (IOException e) {
throw new RuntimeException(e);
}
int readData;
FileInputStream fileInputStream = null;
try {
//创建file......
fileInputStream = new FileInputStream(filepath);
while ((readData = fileInputStream.read())!= -1) {
System.out.println((char)readData);
};
} catch (IOException e) {
e.printStackTrace();
} finally {
//关闭文件流;
try {
fileInputStream.close();
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}
@Test
public void fileIn2() {
String filePath = "D:\\testfile.txt";
int readData;
int readlength = 0;
//字节数组;
byte[] buf = new byte[8];
FileInputStream fileInputStream = null;
try {
//创建FileInputStream对象,用于读取文件;
fileInputStream = new FileInputStream(filePath);
while ((readlength = fileInputStream.read(buf)) != -1) ;
System.out.println(new String(buf, 0, readlength));
}catch (FileNotFoundException ex) {
throw new RuntimeException(ex);
} catch (IOException ex) {
throw new RuntimeException(ex);
}
}
@Test
public void fileIn3(){
String filePath="D:\\test.txt";
int readData;
int readlength=0;
byte[]buf=new byte[8];
FileInputStream fileInputStream = null;
try {
fileInputStream=new FileInputStream(filePath);
while ((readlength=fileInputStream.read(buf))!=-1) {
System.out.println(new String(buf,0,readlength));
};
}catch (IOException e) {
e.printStackTrace();
}finally {
try {
fileInputStream.close();
}catch (IOException e) {
throw new RuntimeException(e);
}
}
}
}
6、OutputStream
查看代码
package FileCreate;
import org.testng.annotations.Test;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
public class outputStream {
public static void main(String[] args) {
}
@Test
public void writeFile(){
String filePath="d:\\fileout.txt";
FileOutputStream fileOutputStream=null;
try{
fileOutputStream=new FileOutputStream(filePath);
//1、写一个字节
//fileOutputStream.write('H');
//2、写一个字符串;
//String str="hello world";
//str.getBytes();
//fileOutputStream.write(str.getBytes);
//3、写入字符串
String str="hello world!";
fileOutputStream.write(str.getBytes(),0,str.length());
} catch (IOException e) {
e.printStackTrace();
}
finally {
try {
fileOutputStream.close();
}catch (IOException e){
throw new RuntimeException(e);
}
}
}
}
7、Scanner与Println
1:基本键盘输入
package FileCreate;
import java.util.Scanner;
public class scanPrintTest {
public static void main(String[] args) {
//创建Scanner对象,接收从控制台输入
Scanner input=new Scanner(System.in);
//接收String类型
String str= input.next();
//输出结果
//System.out.println("str");
System.out.println("hello world!");
}
}
2:常见的键盘输入类型
package FileCreate;
import java.util.Scanner;
public class scanTest {
public static void main(String[] args) {
Scanner input = new Scanner (System.in);
//double数据类型
System.out.print("请输入一个double类型的数");
double d=input.nextDouble();
System.out.println(d);
//int 类型的数
System.out.println("请输入一个int类型的数");
int i =input.nextInt();
System.out.println(i);
//字符串类型的数
System.out.println("请输入一个string类型的数");
String s=input.next();
System.out.println(s);
}
}
8、文件复制
查看代码
package FileCreate;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
public class copyPic {
public static void main(String[] args) throws Exception{
//创建file对象;
File f=new File("D:\\test.jpg");
//判断文件是否存在
if(f.exists()){
System.out.println("test.jpg存在,可以复制");
}
else{
f.createNewFile();
System.out.println("test.jpg不存在,新建成功,可以复制");
}
//创建FilelInputStream对象
FileInputStream inp=new FileInputStream(f);
//创建FileOutputStream对象
// 判断demo目录是否存在
File f1 =new File("D:\\demo");
if(f1.isDirectory()){
FileOutputStream out=new FileOutputStream("d:\\demo\\" +f.getName());
byte bytes[]=new byte[1024];
int temp=0; //边读边写
while((temp = inp.read(bytes))!=-1) { //读
out.write(bytes, 0, temp); //写
// 结束
}
inp.close();
out.close();
System.out.println("文件拷贝成功!");
}else{
//新建demo目录;
f1.mkdir();
System.out.println("demo目录不存在,已新建成功,继续复制");
FileOutputStream out=new FileOutputStream("d:\\demo\\"+f.getName());
byte bytes[]=new byte[1024];
int temp=0;
while((temp=inp.read(bytes))!=-1){
out.write(bytes,0,temp);
}
//结束;
inp.close();
out.close();
System.out.println("文件拷贝成功!");
}
}
}
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· AI编程工具终极对决:字节Trae VS Cursor,谁才是开发者新宠?
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!