一、字符集(常识)
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);
}
}