Java Io读写实例

Java读写IO方法总结

最近学习Java读写文件,总结了以下几种方法:

(1)      个人认为效率最高的还是使用BufferedReader和BufferedWriter读写效率更高。

①  BufferedReader从文件中读取文件。传入的参数分别为路径名与文件名。

public static String ReadeFileBuffered(StringstrPath,String FileName) throws FileNotFoundException

         {

                   Stringstr=null;

                   Filefile=new File(strPath,FileName);

                   //判断文件不存在或者目录不存在存在

                   if(!file.exists()||!file.isDirectory())

                   {

                            thrownew FileNotFoundException();

                   }

                   Readerinfile=new FileReader(file);

                   BufferedReaderreader=new BufferedReader(infile);

                   try{

                            str=reader.readLine();

                            reader.close();

                            infile.close();

                   }catch (IOException e) {

                            //TODO Auto-generated catch block

                            e.printStackTrace();

                   }

                  

                   returnstr;

         }

②  使用BufferedWriter把数据写入文件中。传入的参数分别为路径名与文件名,还有要写进文件的内容。

public static booleanWriteFileBuffered(String strPath,String FileName,String strConcern) throwsIOException

{

           Filefile=new File(strPath,FileName);

           Writeroutfile=new FileWriter(file);

           BufferedWriterwriter=new BufferedWriter(outfile);

           writer.write(strConcern);

           writer.newLine();

           writer.close();

           outfile.close();

           returntrue;

}

(2)      最基本的应该是使用文件字节输入输出流了。就是FileInputStream和FileoutputStream。

①  其中FileInputStream的使用方法如下:        

public static String ReadFile(StringstrPath,String FileName)

    {

             Stringstr="";

             Filefile=new File(strPath,FileName);

             if(!file.exists()||file.isDirectory())

             {

                       try{

                                thrownew FileNotFoundException();

                       }catch (FileNotFoundException e) {

                                // TODO Auto-generated catchblock

                                System.out.println("error:"+e);

                       }

             }

             try{

                       FileInputStreaminfile=new FileInputStream(file);

                       byte[] b=new byte[1024];

                       StringBuffersb=new StringBuffer();

                       try{

                                while(infile.read(b)!=-1)

                                {

                                         sb.append(newString(b));

                                         b=newbyte[1024];

                                }

                                str=sb.toString();

                       }catch (IOException e) {

                                //TODO Auto-generated catch block

                                System.out.println("error:"+e);

                       }

             }catch (FileNotFoundException e) {

                       //TODO Auto-generated catch block

                       System.out.println("error:"+e);

             }

             returnstr;

    }

②  其中FileInputStream的使用方法如下:

//use FileOutputStream Write IO

    publicstatic boolean WriteFile(String strPath,String FileName,String strConcern)

    {

             try

             {

                       Filefile=new File(strPath,FileName);

                       FileOutputStreamoutfile=new FileOutputStream(file);

                       //System.out.println(outfile.);                  

                       byte[]str1=strConcern.getBytes();

                       outfile.write(str1);

                       outfile.close();

                      

             }

             catch(FileNotFoundExceptione)

             {

                       returnfalse;

             }catch (IOException e) {

                       //TODO Auto-generated catch block

                       System.out.println("error+"+e);

                       returnfalse;

             }

             returntrue;

    }

(3)      第三个方法便是使用PrintStream写文件。代码实例如下:

//use PrintStream write IO

   @SuppressWarnings("resource")

   publicstatic boolean WriteFilePrintStream(String strPath,String FileName,StringstrConcern)

   {

            Filefile=new File(strPath,FileName);

            //if(file.exists()||file.isDirectory())

            FileOutputStreamoutfile = null;

            PrintStreamp=new PrintStream(outfile);

            try{

                     outfile= new FileOutputStream(file);

                     p.println(strConcern);

                     try{

                               outfile.close();

                     }catch (IOException e) {

                               //TODO Auto-generated catch block

                               e.printStackTrace();

                     }

                    

            }catch (FileNotFoundException e) {

                     //TODO Auto-generated catch block

                     e.printStackTrace();

            }

  

            returntrue;

   }

(4)      使用文件字符输入输出流:

public static void WriteAndRead()

   {

            FilesourceFile=new File("a.txt");

            FiletargetFile=new File("b.txt");

            chararr[]=new char[9];

            try{

                     Writerw=new FileWriter(targetFile,true);

                     Readerr=new FileReader(sourceFile);

                     intn=-1;

                     while((n=r.read(arr))!=-1)

                     {

                               w.write(arr,0,n);

                     }

                     w.flush();

                     w.close();

            }

            catch(IOExceptione)

            {

                     System.out.println("Error"+e);

            }

   }

(5)      使用随机流读写文件,不需要专门定义是读文件还是写文件,只需要一个随机流解决掉问题,既能读也能写,功能就是强大。

public static void RandomWriteAndRead()throws IOException

   {

            RandomAccessFileinAndOut=null;

            intdata[]={1,2,3,4,5,6,7,8,9,0};

            try{

                     inAndOut=newRandomAccessFile("a.txt","rw");

                     for(inti=0;i<data.length;i++)

                     {

                               inAndOut.writeInt(data[i]);

                              

                     }

                     for(inti=data.length-1;i>=0;i--)

                     {

                               inAndOut.seek(i*4);

                               System.out.printf("\t%d",inAndOut.readInt());

                               //每隔4个字节往前读一个整数

                     }

                     inAndOut.close();

            }catch (FileNotFoundException e) {

                     //TODO Auto-generated catch block

                     System.out.println("Error"+e);

            }

           

   }

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值