IO 文本操作记录

IO 文本操作记录

1、判断文本目录或者文件是否存在,如不存在,可以进行创建dir1.mkdir();删除file.delete();  

1  File dir  =   new File(TXTPATH); // TXTPATH 可以是一个目录或者一个文件的路径。
2  if  ( ! dir.exists()) {
3              flag  =   false ;
4               if  (logger4onln.isInfoEnabled()) {
5                  logger4onln
6                          .info( " [readtxtfile] the file directory isn't exist.  " );
7              }
8               return ;
9         }

 2、 获取该目录下的文件名 

 

String[] filename  =  dir.list(); //  获取该目录下的文件名,形成一个数组
for  ( int  i  =   0 ; i  <  filename.length; i ++
{
// do something 可以通过遍历每个文件名,进行处理
}

3、这里顺便记录一个获取日期的方法:

 

1  Calendar calendarYest  =  Calendar.getInstance();  //  前一天的日期时间
2  calendarYest.add(Calendar.DATE,  - 1 );   //将当前时间的日 减一天。 通过//calendarYest.setTimeZone( new Date().getTime()) 来设置一个自定义时间。
3  int  month  = calendarYest.get(Calendar.MONTH);  //获取月份

4、通过正则表达式判断文件名格式是否正确

 

Pattern pattern  =  Pattern.compile( ""   +  KEY_FILE_NAME
                        
+   " \\d{10} " ); //这里的key_file_name是一种文本命名的固定格式
Matcher matcher 
=  pattern.matcher(fileName);
if  (matcher.find()) 
{
// do something.

5、一个移动文本的方法

 

 1       /**
 2       * 移动文本方法
 3        */
 4       public   static   boolean  removeTo(String from, String to, String fileName) {
 5          File file  =   new  File(from, fileName);
 6           if  (file.isFile()) {
 7              file.renameTo( new  File(to, file.getName()));
 8               return   true ;
 9          }
10           return   false //  移动失败
11      }

 6、案例:需要每小时生成一个文本记录,以小时为单位,超过一小时生成另外一个文本

            SimpleDateFormat format = new  SimpleDateFormat(rsb.getString( " BRASAUTH.DATAFORMAT " ));
            
// SimpleDateFormat format2=new SimpleDateFormat("hhmm");
            String filename = rsb.getString( " BRASAUTH.FILENAME " );
            String path
= rsb.getString( " BRASAUTH.TXTPATH " );
            
            File dir 
=   new  File(path);
            
if ( ! dir.exists())
            
{
                
//如果目录不存在
                dir.mkdir();
            }

            
/**/ /*判断文本,如已经经过一个小时,则另新建一个文本
             * 
             
*/
            
            String fullPath
= path + filename + format.format( new  Date()) + " .txt " ;            
            FileOutputStream outStr 
=   new  FileOutputStream( new  File(fullPath), true );             
            BufferedOutputStream buff 
=   new  BufferedOutputStream(outStr); 
            buff.write(authInfo.getBytes());
            



 

 



你可能感兴趣的:(IO 文本操作记录)