File类
对文件进行创建,删除,以及访问文件内容。
public File(String 路径文件)设置要操作文件的路径
public File(File 父目录 String 路径文件)设置要操作文件的父目录与子文件路径
public boolean createNewFile() throws IOException 文件不存在时创建文件
public boolean delete() 删除文件
public boolean exists()判断文件是否存在
File f = new File("D:\\text.txt");
if (f.exists()){
System.out.println("文件纯在,执行删除"+f.delete());
}else {
System.out.println("文件不存在,执行创建"+f.createNewFile());
}
由于不同平台的路径分隔符不同,所以路径尽可能用常量File.separator来编写
File f = new File("D:"+File.separator+"txt");
在子目录下创建
需要先建立子目录
public boolean mkdir()创建单级目录
public boolean mkdirw() 创建多级目录
public String getParent()获取父路径的信息
public File getParentFile()获取父路径的实例
File f = new File("D:"+File.separator+"demo"+File.separator+"demo2"+File.separator+"demo.txt");
File parentfile = f.getParentFile(); //获取父路径实例 D:/demo/demo2
if (!parentfile.exists()){//判断是否存在
parentfile.mkdirs();//不再存在则创建
}
由于文件创建比较慢,一般采用静态代码块的方式提前创建
private static File f = new File("D:"+File.separator+"demo"+File.separator+"demo2"+File.separator+"demo.txt");
static { File parentfile = f.getParentFile();
if (!parentfile.exists()){
parentfile.mkdirs();
}
}
常用功能
给功能都是根据实例化File文件的路径所决定的
public boolean canExecute() 文件是否能用
public boolean canRead()文件是否能读
public boolean canWrite()文件是否能写
public String getCanonicalPath()得到文件的绝对地址
public boolean isDirectory()是否为目录
public boolean isFile()是否为文件
public long lastModified()得到最后一次修改时间
public long length()文件长度
public String getName()文件名字
public String[] list() 获取该目录下的子目录所有信息
public File[] listFiles()获取该目录下的子目录所有路径信息
public boolean renameTo (File 文件路径) 给文件更名
OutputStream
字节输出流 输出单个字节
该类为抽象类继承Closeable接口和Flashable接口
public abstract void write(int b) throws IOException 写入单个字节
public void write(byte[] b) throws IOException输出全部字节数组
public void write(byte[] b, int off, int len) throws IOException输出部分字节数组
该类的子类Fileoutputstream ,byteArraystream..
Fileoutputstream (文件输出流)
public FileOutputStream(File file) throws FileNotFoundException 设置文件写入路径 (每次写入覆盖)
public FileOutputStream(File file, boolean append) throws FileNotFoundException设置文件写入路径 (append 为true每次写入追加)
OutputStream outputStream = new FileOutputStream(f,true);
outputStream.write("hello".getBytes());
outputStream.close();
InputStream
字节输入流 输入单个字节
该类为抽象类继承Closeable接口
public abstract int read() throws IOException 读取单个字节没有返回-1
public int read(byte[] b) throws IOException读取内容到字节数组
public int read(byte[] b, int off, int len) throws IOException读取部分内容到字节数组
public int available() throws IOException 获取可用长度
该类的子类Fileinputstream 同文件输出流
Writer
字符输出流
该类为抽象类继承Closeable接口和Flashable接口和Appendable接口
方法同OutputStream类
public Writer append(char c) throws IOException追加字符
Reader
字符输入流
该类为抽象类继承Closeable接口Readable接口
方法同intputStream类
Outputstream,InputSteam同Writer,Reader的区别就是一个是处理字节一个是处理字符。
使用字节比较多,文件传输一般使用字节。字符常用与中文处理,字符流实则在缓冲区转化为字节流来处理。

