文件的读取与写入

 //文件的创建-creat

File writename = new File("d://output.txt"); // 相对路径,如果没有则要建立一个新的output。txt文件  

        writename.createNewFile(); // 创建新文件  

        BufferedWriter out = new BufferedWriter(new FileWriter(writename));

out.write(buffer); // \r\n即为换行  
        out.flush(); // 把缓存区内容压入文件  

        out.close(); // 最后记得关闭文件 


//文件的读取

public static void readFileByRandomAccess(String fileName) {  



        RandomAccessFile randomFile = null;  


        try {  


            System.out.println("随机读取一段文件内容:");  


            // 打开一个随机访问文件流,按只读方式  


            randomFile = new RandomAccessFile(fileName, "r");  


            // 文件长度,字节数  


            long fileLength = randomFile.length();  


            // 读文件的起始位置  


            int beginIndex = (fileLength > 4) ? 0 : 0;  


            // 将读文件的开始位置移到beginIndex位置。  


            randomFile.seek(beginIndex);  


            byte[] bytes = new byte[10];  


            int byteread = 0;  


            // 一次读10个字节,如果文件内容不足10个字节,则读剩下的字节。  


            // 将一次读取的字节数赋给byteread  
            String tr = "";
            while ((byteread = randomFile.read(bytes)) != -1) {  


                System.out.write(bytes, 0, byteread);  


            }  


        } catch (IOException e) {  


            e.printStackTrace();  


        } finally {  


            if (randomFile != null) {  


                try {  


                    randomFile.close();  


                } catch (IOException e1) {  


                }  


            }  


        }  


    }   

/** 


      * 以行为单位读取文件,常用于读面向行的格式化文件 


      */  


   public static String readFileByLines(String fileName) {  


   String content = "";
       File file = new File(fileName);  


       BufferedReader reader = null;  
       String tempString = null;  
       try {  


           System.out.println("以行为单位读取文件内容,一次读一整行:");  


           reader = new BufferedReader(new FileReader(file));  


           


           int line = 1;  


           // 一次读入一行,直到读入null为文件结束  


           while ((tempString = reader.readLine()) != null) {  


               // 显示行号  


               System.out.println("line " + line + ": " + tempString);  
               content+=tempString;
               line++;  


           }  


           reader.close();  


       } catch (IOException e) {  


           e.printStackTrace();  


       } finally {  


           if (reader != null) {  


               try {  


                   reader.close();  


               } catch (IOException e1) {  


               }  


           }  


       }  


       return content;
   }  

猜你喜欢

转载自blog.csdn.net/qq_37996327/article/details/80809856
今日推荐