io操作的4个基本步骤 1.创建file对象 2.选择字符流还是字节流 3.操作,是读还是写 4.释放资源
编码:字符—>字节 解码:字节—>字符 编码解码过程要使用相同的char-set 否则会出现乱码
此处代码使用的是eclipse编写。工程默认代码为gbk。
import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; /* * 字节输出流 * * 1.创建源 * 2.选择流 * 3.操作(写) * 4.释放资源 */ public class IO_Test03 { public static void main(String[] args) { // TODO Auto-generated method stub File desFile = new File("testWrite.txt"); File srcFile = new File("io.txt"); OutputStream oStream = null; InputStream iStream = null; try { iStream = new FileInputStream(srcFile); oStream = new FileOutputStream(desFile); int inputTemp = -1; byte[] inputFlush = new byte[1024]; while ((inputTemp = iStream.read(inputFlush)) != -1) { oStream.write(inputFlush, 0, inputFlush.length); } } catch (Exception e) { // TODO: handle exception } finally { try { if (oStream != null) oStream.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } }