注册 登录
编程论坛 J2EE论坛

通过文件操作FileOut/InputStream的详细过程

发布于 2010-05-09 10:08, 969 次点击
package com.yds.entity.test;

import
import
import
import
import java.util.Scanner;

public class Inputtest {
    // 练习输入文件,按什么结束
    //通过FileOutputStream
    public static void main(String[] args) {
        FileOutputStream fos = null;
        FileOutputStream fos1 = null;
        FileInputStream fis = null;
        try {
            fos = new FileOutputStream("d:/test11.txt");
        } catch (FileNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        loope: while (true) {
            String inp = input() + "\r\n";// 得到一句话之后,以回车结束
            String b[] = inp.split(" ");// 把得到字符串按空格分开
            String b1 = b[b.length - 1].trim();// 得到输入的最后一个字符串,并把前后空格去掉
            if ("end".equals(b1)) {// 将最后一个值拿出来与end比较
                // System.out.println("11111");
                break loope;// 退出到指定的loope的位置
            } else {
                byte[] bt = inp.getBytes();// 将字符串转为字节数组
                try {
                    fos.write(bt);// 然后写到文件中
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
        }
        try {
            fis = new FileInputStream("d:/test11.txt");// 读取硬盘上的文件
            byte[] b = new byte[1024];// 设定要读取文件的大小
            int l = fis.read(b);// 读入文字
            System.out.println(new String(b, 0, l));// 读出文件,并写下
            String m=new String(b, 0, l);//将读出的值放到一个字符串
            //System.out.println(m);
            fos1 = new FileOutputStream("d:/test12.txt");//在新建一个文件
            fos1.write(m.getBytes());//将读到的值,在写入到另一个文件
            System.out.println("操作成功");
        } catch (FileNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

    public static String input() {
        return new Scanner(System.in).nextLine();
    }
}
3 回复
#2
aina2010-05-17 21:00
不错,怎么没有人回复呢?
#3
baifenghan2010-05-18 21:43
请改掉你使用标签的这个习惯吧,一种看起来就难受的风格,至于坏处大家都知道了。
#4
baifenghan2010-05-20 22:22
不错,好好搞
1