文件操作

1.读取txt文件内容

// 从txt文件中读取字符
File txtxfile = new File("C:\\Users\\Administrator\\Desktop\\test.txt");
FileInputStream fr = new FileInputStream(txtxfile);
InputStreamReader isr = new InputStreamReader(fr, "GBK");
BufferedReader br = new BufferedReader(isr);
String len;
while ((len = br.readLine()) != null) {
        System.out.println(len);
}

2.向txt文件写入字符

File txtxfile = new File("C:\\Users\\Administrator\\Desktop\\test.txt");
FileWriter fw = new FileWriter(txtxfile);
BufferedWriter br = new BufferedWriter(fw);
br.write("666\r\n");
br.close();

3.遍历某个文件夹的所有文件 且将文件后缀为html的文件拷贝到另一个文件夹中

static void showfile(File file) throws IOException {
        String newfiledir = "C:\\Users\\Administrator\\Desktop\\Copy";
        if (file.exists()) {
                File[] filelist = file.listFiles();
                for (int i = 0; i < filelist.length; i++) {
                        if (filelist[i].isFile()) {
                                String fileName = filelist[i].getName();
                                String suffix = fileName.substring(fileName.lastIndexOf(".") + 1);
                                if (suffix.equals("html")) {
                                        copyFile(filelist[i], new File(newfiledir + "\\" + filelist[i].getName()));
                                        System.out.println(filelist[i].getAbsolutePath());
                                }
                        } else {
                                showfile(filelist[i]);
                        }
                }
        } else {
                System.out.println("该文件夹不存在!");
        }
}

public static void copyFile(File sourceFile, File targetFile) throws IOException {
        //sourceFile 源文件  targetFile 目标文件

        // 新建文件输入流并对它进行缓冲
        FileInputStream fis = new FileInputStream(sourceFile);
        BufferedInputStream bis = new BufferedInputStream(fis);
        // 新建文件输出流并对它进行缓冲
        FileOutputStream fos = new FileOutputStream(targetFile);
        BufferedOutputStream bos = new BufferedOutputStream(fos);
        // 缓冲数组
        byte[] b = new byte[1024 * 1024];
        int len;
        while ((len = bis.read(b)) != -1) {
                bos.write(b, 0, len);
        }
        // 刷新此缓冲的输出流
        bos.close();
        //关闭流
        bos.close();
        bis.close();
        fos.close();
        fis.close();

}

转载于:https://my.oschina.net/u/4100033/blog/3051751

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值