java吧 关注:1,298,423贴子:12,837,299
  • 5回复贴,共1

新人求问I/O操作问题。。。学完Java的能不能过来帮帮忙

只看楼主收藏回复

描述:用字节流处理二进制数据
问题:从in.txt拷贝到out.txt。无法拷贝,in.txt的输入数据还被清零了
代码在二楼


1楼2016-05-08 11:12回复
    import java.io.FileInputStream;
    import java.io.FileNotFoundException;
    import java.io.FileOutputStream;
    import java.io.IOException;
    import java.util.Scanner;
    class Copy{
    public static void copy(String from,String to){
    FileInputStream fis=null;
    FileOutputStream fos=null;
    try{
    fis=new FileInputStream(from);
    fos=new FileOutputStream(to);//文件若不存在,自动生成
    byte[] b=new byte[1024];
    int length;
    while((length=fis.read(b))!=-1){
    fos.write(b,0,length);
    }
    }catch (FileNotFoundException e){
    e.printStackTrace();
    }catch(IOException e){
    e.printStackTrace();
    }finally{
    try{
    fos.close();
    fis.close();
    }catch (IOException e){
    e.printStackTrace();
    }
    }
    }
    }
    class MyWriter{
    private String filename;
    public MyWriter(String filename){
    this.filename=filename;
    }
    public String getFilename(){
    return filename;
    }
    public void setFilename(String filename){
    this.filename=filename;
    }
    public void write(){
    FileOutputStream fos=null;
    try{
    fos=new FileOutputStream(filename);
    Scanner sc=new Scanner(System.in);
    String txt=null;
    while(!"over".equalsIgnoreCase((txt=sc.nextLine()))){
    fos.write(txt.getBytes());
    fos.write("\r\n".getBytes());
    }
    }catch (FileNotFoundException e){
    e.printStackTrace();
    }catch (IOException e){
    e.printStackTrace();
    }finally{
    try{
    if(fos!=null)
    fos.close();
    }catch(IOException e){
    e.printStackTrace();
    }
    }
    }
    }
    public class test{
    public static void main(String[] args){
    MyWriter mw=new MyWriter("D:\\in.txt");
    mw.write();
    Copy.copy("D:\\in.txt", "D:\\out.txt");
    }
    }


    2楼2016-05-08 11:13
    回复
      2026-03-01 10:25:55
      广告
      不感兴趣
      开通SVIP免广告
      我把你的代码在Eclipse中和命令行中都运行了。没问题啊。


      3楼2016-05-08 12:08
      收起回复
        转发文章把你凭弊了是怎么回事


        4楼2016-05-08 12:08
        回复