如果要进行所有的文件以及文件内容的开发操作,应该使用java.io包完成,而在此包中有五个核心类和一个接口
五个核心类:File , InputStream ,OutputStream , Reader ,Writer
一个核心接口:Serializable
File类
构造方法:
设置完整路径:public File(String pathname)
大部分情况下使用此操作
设置父路径与子文件路径:public File(File parent,String child)
在Android上使用
创建文件:
public boolean createNewFile()throws IOException
可能抛出异常的原因:
1. 目录不能访问
2. 文件重名或者文件名称错误
import java.io.File;
public class Demo {
public static void main(String[] args) throws Exception{
File file=new File("e:\\test.txt");
System.out.println(file.createNewFile());
}
}
注意:之所以将路径写成 e:\test.txt,而不是e:\test.txt是因为直接写\t会当做是制表符
此时运行,返回true,在E盘中即可找到test.txt文件
删除文件:
public boolean delete()
public class Demo1 {
public static void main(String[] args) throws IOException {
// TODO Auto-generated method stub
File file=new File("e:\\test.txt");
if(file.exists()){ //如果文件存在,执行文件的删除,否则执行文件的创建
file.delete();
}else{
System.out.println(file.createNewFile());
}
}
}
判断文件是否存在:file.exists()
注意: 在写路径是,Windows系统使用“\”,而Linux使用的是“/”
解决方法:File类中有一个常量separator,来表示分隔符
因此可以写为:
"e:"+File.separate+"test.txt"
创建目录:
如果此时我们将路径改为
"e:"+File.separate+"hello"+File.separate"test.txt"
但是E盘中并不存在hello目录文件,此时我们来创建目录
找到父路径:
public File getParentFile();
注意:返回值是File,可以使用File中的方法
创建目录:
public boolean mkdir() //创建一个目录
public boolean mkdirs() //创建多个目录
public static void main(String[] args) throws IOException {
// TODO Auto-generated method stub
File file=new File("e:"+File.separator+"hello"+File.separator+"src"+File.separator+"test.txt");
if(!file.getParentFile().exists()){ //判断父路径是否存在
file.getParentFile().mkdirs(); //创建父路径
}
if(file.exists()){
file.delete();
}else{
System.out.println(file.createNewFile());
}
File中的一些类:
取得文件大小:
public long length() //按字节返回
判断是否是文件:
public boolean isFile()
判断是否是目录:
public boolean isDirectory()
得到文件路径:
public String getPath()