喜欢研究学习技术,喜欢和志同道合的人交流。 从事测试6年,专职性能3年经验,擅长性能测试,测试框架开发。 励志格言:只要想学习,永远都不会太晚;只要想进步,永远都会有空间。

java之IO读写文件操作

上一篇 / 下一篇  2014-11-12 22:32:28 / 个人分类:java开发技术

package com.test;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

public class copyFile {
 /**
  *文件复制
  *1、File
  * 2、 IO
  */
 private void copy(String startName, String endName) {
  InputStream is = null;
  OutputStream s = null;

  try {
   File startFile = new File(startName);
   File endFile = new File(endName + "\\" + startFile.getName());

   if (!endFile.exists()) {
    endFile.createNewFile();
   }
   //读取
   is=new FileInputStream(startFile);
   
   //写入
   os=new FileOutputStream(endFile);
   
   byte[] b=new byte[1024];
   
   //好处:避免传输音频,视频,图片时,出现丢失
   //坏处:如果传输的文件过大,过于占用内存,甚至出现内存溢出。
   byte[] inputb=new byte[(int)startFile.length()];
   
   int num=0;
   //读取文件中的信息
   while((num=is.read(inputb))!=-1){
    //写入到目的路径
    String name=new String(inputb,0,num);
    os.write(inputb,0,num);
    os.flush();
    
   }
   
  } catch (IOException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  }finally{
   try {
    if(is!=null){
     is.close();
    }
    if(os!=null){
     os.close();
    }
   } catch (Exception e2) {
    // TODO: handle exception
    e2.printStackTrace();
   }
  }

 }

 public static void main(String[] args) {
  String startName="E:\\123.txt";
  String endName="F:";
  new copyFile().copy(startName, endName);

 }

}


TAG:

 

评分:0

我来说两句

Open Toolbar