文件操作一

一、             File

File是整个java.io包中一个独立的类。此类的功能是完成与整个java平台无关的文件操作。

创建文件示例代码如下:

import java.io.File;

public class FileDemo1 {

   public static void main(String[] args) throws Exception{

     // TODO Auto-generated method stub

     File file=new File("c:"+File.separator+"hi.demo");

     if(!file.exists()) file.createNewFile();

   }

}

二、             字节输出流:

字节和字符最大的区别在于,字节不需要缓存,而字符需要缓存。

字节输出流最大的父类是:OutputStream。需要子类实例化,示例代码如下:

import java.io.File;

import java.io.FileOutputStream;

import java.io.IOException;

import java.io.OutputStream;

public class FileOutputStreamDemo {

   public static void main(String[] args) throws IOException {

     // TODO Auto-generated method stub

     File file=new File("c:"+File.separator+"hi.txt");

     if(!file.exists()) file.createNewFile();

     OutputStream out=new FileOutputStream(file);

     String str="hello world";

     byte[] bytes=str.getBytes();

     out.write(bytes);

     out.close();

   }

}

三、             字节输入流

最大的父类是:InputStream,示例代码如下:

import java.io.File;

import java.io.FileInputStream;

import java.io.FileNotFoundException;

import java.io.InputStream;

public class FileInputStreamDemo {

   /**

    * @param args

    * @throws FileNotFoundException 

    */

   public static void main(String[] args) throws Exception {

     File f=new File("c:"+File.separator+"hi.txt");

     InputStream in=new FileInputStream(f);

     byte[]  b=new byte[(int) f.length()];

     int len=in.read(b);

     System.out.println(new String(b,0,len));

     in.close();

   }

}

四、             字符输出流

Writer:字符输出流,示例代码如下:

import java.io.File;

import java.io.FileWriter;

import java.io.Writer;

public class WriterDemo {

   public static void main(String[] args) throws Exception {

     // TODO Auto-generated method stub

     File file=new File("c:"+File.separator+"hi.txt");

     Writer w=new FileWriter(file,true);

     w.write("this is is writer");

     w.close();

   }

}

原文地址:https://www.cnblogs.com/itfenqing/p/4429546.html