[Java]读取文件方法大全

2011年6月11日 05:08

看到很好用的代码调用IO读取文件,转载到这里

原文链接:http://blog.csdn.net/homebei2/archive/2011/03/16/6254707.aspx

public   class  ReadFromFile {
     /**
     * 以字节为单位读取文件,常用于读二进制文件,如图片、声音、影像等文件。
      */
     public   static   void  readFileByBytes(String fileName) {
        File file  =   new  File(fileName);
        InputStream in  =   null ;
         try  {
            System.out.println( " 以字节为单位读取文件内容,一次读一个字节: " );
             //  一次读一个字节
            in  =   new  FileInputStream(file);
             int  tempbyte;
             while  ((tempbyte  =  in.read())  !=   - 1 ) {
                System.out.write(tempbyte);
            }
            in.close();
        }  catch  (IOException e) {
            e.printStackTrace();
             return ;
        }
         try  {
            System.out.println( " 以字节为单位读取文件内容,一次读多个字节: " );
             //  一次读多个字节
             byte [] tempbytes  =   new   byte [ 100 ];
             int  byteread  =   0 ;
            in  =   new  FileInputStream(fileName);
            ReadFromFile.showAvailableBytes(in);
             //  读入多个字节到字节数组中,byteread为一次读入的字节数
             while  ((byteread  =  in.read(tempbytes))  !=   - 1 ) {
                System.out.write(tempbytes,  0 , byteread);
            }
        }  catch  (Exception e1) {
            e1.printStackTrace();
        }  finally  {
             if  (in  !=   null ) {
                 try  {
                    in.close();
                }  catch  (IOException e1) {
                }
            }
        }
    }

     /**
     * 以字符为单位读取文件,常用于读文本,数字等类型的文件
      */
     public   static   void  readFileByChars(String fileName) {
        File file  =   new  File(fileName);
        Reader reader  =   null ;
         try  {
            System.out.println( " 以字符为单位读取文件内容,一次读一个字节: " );
             //  一次读一个字符
            reader  =   new  InputStreamReader( new  FileInputStream(file));
             int  tempchar;
             while  ((tempchar  =  reader.read())  !=   - 1 ) {
                 //  对于windows下,\r\n这两个字符在一起时,表示一个换行。
                 //  但如果这两个字符分开显示时,会换两次行。
                 //  因此,屏蔽掉\r,或者屏蔽\n。否则,将会多出很多空行。
                 if  ((( char ) tempchar)  !=   ' \r ' ) {
                    System.out.print(( char ) tempchar);
                }
            }
            reader.close();
        }  catch  (Exception e) {
            e.printStackTrace();
        }
         try  {
            System.out.println( " 以字符为单位读取文件内容,一次读多个字节: " );
             //  一次读多个字符
             char [] tempchars  =   new   char [ 30 ];
             int  charread  =   0 ;
            reader  =   new  InputStreamReader( new  FileInputStream(fileName));
             //  读入多个字符到字符数组中,charread为一次读取字符数
             while  ((charread  =  reader.read(tempchars))  !=   - 1 ) {
                 //  同样屏蔽掉\r不显示
                 if  ((charread  ==  tempchars.length)
                         &&  (tempchars[tempchars.length  -   1 ]  !=   ' \r ' )) {
                    System.out.print(tempchars);
                }  else  {
                     for  ( int  i  =   0 ; i  <  charread; i ++ ) {
                         if  (tempchars[i]  ==   ' \r ' ) {
                             continue ;
                        }  else  {
                            System.out.print(tempchars[i]);
                        }
                    }
                }
            }

        }  catch  (Exception e1) {
            e1.printStackTrace();
        }  finally  {
             if  (reader  !=   null ) {
                 try  {
                    reader.close();
                }  catch  (IOException e1) {
                }
            }
        }
    }

     /**
     * 以行为单位读取文件,常用于读面向行的格式化文件
      */
     public   static   void  readFileByLines(String fileName) {
        File file  =   new  File(fileName);
        BufferedReader reader  =   null ;
         try  {
            System.out.println( " 以行为单位读取文件内容,一次读一整行: " );
            reader  =   new  BufferedReader( new  FileReader(file));
            String tempString  =   null ;
             int  line  =   1 ;
             //  一次读入一行,直到读入null为文件结束
             while  ((tempString  =  reader.readLine())  !=   null ) {
                 //  显示行号
                System.out.println( " line  "   +  line  +   " :  "   +  tempString);
                line ++ ;
            }
            reader.close();
        }  catch  (IOException e) {
            e.printStackTrace();
        }  finally  {
             if  (reader  !=   null ) {
                 try  {
                    reader.close();
                }  catch  (IOException e1) {
                }
            }
        }
    }

     /**
     * 随机读取文件内容
      */
     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 )  ?   4  :  0 ;
             //  将读文件的开始位置移到beginIndex位置。
            randomFile.seek(beginIndex);
             byte [] bytes  =   new   byte [ 10 ];
             int  byteread  =   0 ;
             //  一次读10个字节,如果文件内容不足10个字节,则读剩下的字节。
             //  将一次读取的字节数赋给byteread
             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) {
                }
            }
        }
    }

     /**
     * 显示输入流中还剩的字节数
      */
     private   static   void  showAvailableBytes(InputStream in) {
         try  {
            System.out.println( " 当前字节输入流中的字节数为: "   +  in.available());
        }  catch  (IOException e) {
            e.printStackTrace();
        }
    }

     public   static   void  main(String[] args) {
        String fileName  =   " C:/temp/newTemp.txt " ;
        ReadFromFile.readFileByBytes(fileName);
        ReadFromFile.readFileByChars(fileName);
        ReadFromFile.readFileByLines(fileName);
        ReadFromFile.readFileByRandomAccess(fileName);
    }
}

5、将内容追加到文件尾部
public   class  AppendToFile {
     /**
     * A方法追加文件:使用RandomAccessFile
      */
     public   static   void  appendMethodA(String fileName, String content) {
         try  {
             //  打开一个随机访问文件流,按读写方式
            RandomAccessFile randomFile  =   new  RandomAccessFile(fileName,  " rw " );
             //  文件长度,字节数
             long  fileLength  =  randomFile.length();
             // 将写文件指针移到文件尾。
            randomFile.seek(fileLength);
            randomFile.writeBytes(content);
            randomFile.close();
        }  catch  (IOException e) {
            e.printStackTrace();
        }
    }

     /**
     * B方法追加文件:使用FileWriter
      */
     public   static   void  appendMethodB(String fileName, String content) {
         try  {
             // 打开一个写文件器,构造函数中的第二个参数true表示以追加形式写文件
            FileWriter writer  =   new  FileWriter(fileName,  true );
            writer.write(content);
            writer.close();
        }  catch  (IOException e) {
            e.printStackTrace();
        }
    }

     public   static   void  main(String[] args) {
        String fileName  =   " C:/temp/newTemp.txt " ;
        String content  =   " new append! " ;
         // 按方法A追加文件
        AppendToFile.appendMethodA(fileName, content);
        AppendToFile.appendMethodA(fileName,  " append end. \n " );
         // 显示文件内容
        ReadFromFile.readFileByLines(fileName);
         // 按方法B追加文件
        AppendToFile.appendMethodB(fileName, content);
        AppendToFile.appendMethodB(fileName,  " append end. \n " );
         // 显示文件内容
        ReadFromFile.readFileByLines(fileName);
    }
} 

评论(5) 阅读(2910)

高手经典的Emacs配置文件 (cedet+ecb+cscope)

2011年6月03日 04:54

Emacs 23在ubuntu12.04下的配置。样式美观,功能强耐用齐全,可自己定义想要的功能。包括:
在左边显示行号
语法高亮
显示括号匹配
禁止自动保存
编译成功后自动关闭*compilation* buffer
缩进策略
输入左边的括号,就会自动补全右边的部分.包括(), "", [] , {} , 等等。

新增加了color theme。所有配置文件在:git clone https://github.com/ysonggit/emacs-ubuntu1204.git

评论(4) 阅读(9667)

Linux 定时关机-shutdown命令参数

2011年5月08日 18:53

一、shutdown命令关机
  各参数功能:
  -c 取消前一个shutdown命令。
  -f 重新启动时不执行fsck(注:fsck是Linux下的一个检查和修复文件系统的程序)。
  -F 重新启动时执行fsck。  -h 将系统关机,在某种程度上功能与halt命令相当。
  -k 只是送出信息给所有用户,但并不会真正关机。
  -n 不调用init程序关机,而是由shutdown自己进行(一般关机程序是由shutdown调用init来实现关机动作),使用此参数将加快关机速度,但是不建议用户使用此种关机方式。
  -r 关机之后重新启动系统。
表示立即执行,now=+0
  -f<秒数> 送出警告信息和关机信号之间要延迟多少秒。警告信息将提醒用户保存当前进行的工作。

  [时间] 设置多久时间后执行shutdown命令。
时间参数有hh:mm或+m两种模式。hh:mm格式表示在几点几分执行shutdown命令。例如 “shutdown 10:45”表示将在10:45执行shutdown。+m表示m分钟后执行shutdown。比较特别的用法是以now表示立即执行shutdown。 值得注意的是这部分参数不能省略。
1、定时关机sudo shutdown -h 23:00  //表示在23点定时关机
2、延时关机sudo shutdown +minutes(这个加号不可省略,minutes表示分钟)比如: sudo shutdown -h +120  //两小时候关机
3、取消前一个关机命令按“Ctrl+C”键或输入命令:shutdown -c

二、编写脚本文件关机
1、先用nano编辑器建立一个文件,如guanji.sh
sudo nano guanji.sh输入如下内容:
#! /bin/shshutdown -h 23:00  //表示晚上23点00分关机,并关闭电源。
2、给脚本可执行权限右键此文件,选择属性->权限,最下方会有一个“允许以程序执行文件”,将这一项勾选,就可以了。
或在命令行下附予权限:
chmod 777 test.sh或: chmod +x test.sh
3、执行脚本命令或双击运行。#sh guanji.sh

评论(3) 阅读(3892)

一行命令找回ubuntu下丢失的系统菜单

2011年5月02日 11:24

因为是wubi的系统,不太稳定。莫名地桌面左上角的系统下拉菜单不见了。用一行命令即可轻松找回:

cp /etc/xdg/menus/applications.menu ~/.config/menus/applications.menu

http://forum.ubuntu.org.cn/viewtopic.php?f=80&t=129568

评论(3) 阅读(4673)