标签:style blog io ar color os 使用 sp for
1 使用FileReader,FileWriter只能实现文本文件的复制,和FileInputStream,FileOutputStream区别在于,读入的是char类型的数据
2 对于非文本文件(视频文件,音频,图片等),只能使用字节流
package lianxi1; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; import org.junit.Test; public class TestFileInputStream { @Test //要读取的文件一定要存在 public void test1(){ FileInputStream fis = null; try { File file1 = new File("d:\\io\\helloworld.txt"); fis = new FileInputStream(file1); int b = fis.read(); while(b!=-1){ System.out.print((char)b); b = fis.read(); } } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } finally{ try { fis.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } @Test // 要读取的文件一定要存在 public void test2() { FileInputStream fis = null; try { File file1 = new File("d:\\io\\helloworld.txt"); fis = new FileInputStream(file1); byte[] b = new byte[6]; int len; // int len = fis.read(b); // while (len != -1) { // for(int i=0;i<len;i++){ // System.out.print((char)b[i]); // } // len = fis.read(b); // } while ((len=fis.read(b))!= -1) { //注意 b是存储数据的缓冲器,len是返回读入缓冲区的字节总数 //所以len<=b.length for(int i=0;i<len;i++){ //是len,不是b.length System.out.print((char)b[i]); } } } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } finally { try { fis.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } }package lianxi1; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import org.junit.Test; public class TestFileOutputStream { @Test //要写入的文件不一定要存在,不存在可以被创建,存在的话内容会被覆盖 public void test1(){ FileOutputStream fos = null; try { File file1 = new File("GoodMood"); fos = new FileOutputStream(file1); fos.write(new String("Have a good night!").getBytes()); } catch (Exception e) { e.printStackTrace(); } finally{ try { fos.close(); } catch (IOException e) { e.printStackTrace(); } } } @Test //从一个文件中读入数据,写入另一个文件 public void test2(){ FileInputStream fis = null; FileOutputStream fos = null; try{ File file1 = new File("d:/io/helloworld.txt"); File file2 = new File("GoodMood"); fis = new FileInputStream(file2); fos = new FileOutputStream(file1); int len; byte[] b = new byte[4]; while((len = fis.read(b))!=-1){ fos.write(b, 0, len); } }catch(Exception ex){ ex.printStackTrace();} finally{ if(fis!=null){ try { fis.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } if(fos!=null){ try { fos.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } } }
标签:style blog io ar color os 使用 sp for
原文地址:http://www.cnblogs.com/yjtm53/p/4156391.html