Java常用API (字符集、资源释放、IO工具)

一、字符集(常识)

  • ISO-8895-1,又称为 ladin1码,仅支持英文。

  • GBK,国标扩展码,支持常见中文(简体、繁体)

  • UTF-8,万国码,支持不同国家的不同符号。

二、资源释放(新语法)

1.拷贝业务(JDK1.7前的语法 )

package com.czxy.d2_io_close;

import java.io.*;


public class TestIO_close {
    public static void main(String[] args) throws IOException {
        //文件的拷贝
        InputStream is = null;
        OutputStream os = null;
        try{
            //拷贝业务
            //1 准备流:input读 a.txt, ouput写 b.txt
            is = new FileInputStream(new File("a.txt"));
            os = new FileOutputStream(new File("b.txt"));
            //2 操作:一边读,一边写
            int b;
            while( (b = is.read()) != -1) {
                //b存放读到一个字符
                os.write(b);
            }
            //模拟错误(异常)
            //int i = 1/0;
            System.out.println("拷贝完成");
        } catch (Exception e) {
            //错误处理
        } finally {
            //释放资源(正常、异常,都执行)
            if(os != null) {
                os.close();
            }
            if(is != null) {
                is.close();
            }
        }

    }
}

2.拷贝业务(JDK1.7后的语法 )

package com.czxy.d2_io_close;

import java.io.*;

public class TestIO_close_try {
    public static void main(String[] args) throws IOException {
        try(
            //此处内容,自动释放资源 (jdk1.7之后的语法)
            InputStream is = new FileInputStream(new File("a.txt"));
            OutputStream os = new FileOutputStream(new File("b.txt"));
        ){
            //2 操作:一边读,一边写
            int b;
            while( (b = is.read()) != -1) {
                //b存放读到一个字符
                os.write(b);
            }
            //模拟错误(异常)
            //int i = 1/0;
            System.out.println("拷贝完成");
        } catch(Exception e) {
            //错误处理
        }
    }
}

三、IO工具

  • IO 工具:commons-io,有apache第三方组织开源项目,对使用者提供jar包(java程序压缩文件)。

步骤1:拷贝jar包

步骤2:启用jar包(将jar包应用到项目中)

步骤3:使用jar的内容

package com.czxy.d3_io_util;

import org.apache.commons.io.FileUtils;

import java.io.File;
import java.io.IOException;

public class TestCommonsIO {
    public static void main(String[] args) throws IOException {
        //0 确定文件位置
        File aFile = new File("a.txt");

        //1 读操作
        String data = FileUtils.readFileToString(aFile, "UTF-8");
        System.out.println(data);

        //2 写操作
        FileUtils.writeStringToFile(aFile,"\r\n厉害呀!!", "UTF-8", true);
    }
}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值