栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

Java file类

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

Java file类

File类是io包中唯一代表磁盘文件本身的对象,可以通过调用File类中的方法,实现创建、删除、重命名文件等。

1. 文件的创建与删除
  可以使用File类创建一个文件对象,三种构造方法的语法格式如下:

new File(String pathname)
new File(String parent, String child)
new File(File f, String child)

pathname是路径名称,parent是父路径字符串,child是子路径字符串,f是父路径对象。如下例:

File file = new File("E:/test.txt");
File file = new File("E:/myword","word.txt");

如果E:/myword目录下没有名称为word的文件,File类对象可通过createNewFile()方法创建一个名称为word.txt的文件;如果存在,可通过delete()方法将其删除。

  1. 获取文件长度
import java.io.File;

public class FileTest {

    public static void main(String[] args) {
        File file = new File("E:/myword", "word.txt");    // 创建文件对象
        if(file.exists()) {    // 判断文件是否存在
            String name = file.getName();    // 获取文件名称
            long length = file.length();    // 获取文件长度
            boolean hidden = file.isHidden();    // 判断文件是否是隐藏文件

            System.out.println("文件名称:" + name);
            System.out.println("文件长度是:" + length);
            System.out.println("是否是隐藏文件:" + hidden);
        } else {
            System.out.println("文件不存在");
        }
    }

}

带缓存的输入/输出流
  缓存是I/O的一种性能优化。缓存流为I/O流增加了内存缓存区。

1. BufferedInputStream类与BufferedOutputStream类
  构造函数如下:

BufferedInputStream(InputStream in)
BufferedInputStream(InputStream in, int size)
BufferedOutputStream(OutputStream in)
BufferedOutputStream(OutputStream in, int size)

在使用BufferedWriter类的write()方法时,数据并没有立刻被写入到输出流时,而是首先进入缓存区中,如果想立刻将缓冲区中的数据写入输出流中,一定要调用flush()方法。

数据输入/输出流
数据输入/输出流为DataInputStream类与DateOutputStream类,允许应用程序以与机器无关的方式从底层输入流中读取基本Java数据类型。

构造方法如下:

DataInputStream(InputStream in)
DataOutputStream(OutputStream out)

DataOutputStream类提供了以下三种写入字符串的方法:

writeBytes(String s)
writeChars(String s)
writeUTF(String s)
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/343421.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号