查看完整版本: 简单文件写入与读取

sunnyone 2008-7-27 15:18

简单文件写入与读取

分别用FileInputStream、FileOutputStream 与FileWriter 、FileReader写一个将一字符串写入文件,然后把内容输出

import java.io.*;
public class FileStreamTest {
       
        public static void main(String[] args) throws Exception{
                // TODO: Add your code here
                FileOutputStream out = new FileOutputStream("test.txt");
                out.write("www.newwhy.com".getBytes());
                out.close();//此处不用close()方法也能写入,因为FileOutputStream类会调用flush()方法进行写入磁盘
               
                byte [] buff = new byte[1024];
                File file = new File("test.txt");
                FileInputStream in = new FileInputStream(file);
                int len =in.read(buff);
                System.out.println(new String(buff,0,len));
                in.close();
               
               
               
        }       
               
}





import java.io.*;
public class FileWriterTest {
        /**
         
         */
        public static void main(String[] args) throws Exception{
                // TODO: Add your code here
                FileWriter write = new FileWriter("test2.txt");
                write.write("www.newwhy.com");
                write.close();//此处若不用close()方法,则字符不会写入磁盘,编译能通过,运行时报错
                                             
                char[] buff = new char[1024];
                FileReader r = new FileReader("test2.txt");
                int len = r.read(buff);
                //System.out.println(new String(buff,0,len));
                System.out.println(new String (buff,0,len));
                r.close();
               
               
        }       
}
页: [1]
查看完整版本: 简单文件写入与读取