Chinaunix首页 | 论坛 | 博客
  • 博客访问: 2297725
  • 博文数量: 321
  • 博客积分: 3440
  • 博客等级: 中校
  • 技术积分: 2992
  • 用 户 组: 普通用户
  • 注册时间: 2007-05-24 09:08
个人简介

我就在这里

文章分类

全部博文(321)

文章存档

2015年(9)

2014年(84)

2013年(101)

2012年(25)

2011年(29)

2010年(21)

2009年(6)

2008年(23)

2007年(23)

分类: Java

2013-06-24 09:03:13

转自:http://bluerose.iteye.com/blog/1167211

  1. 一、多种方式读文件内容。

  2. 1、按字节读取文件内容
  3. 2、按字符读取文件内容
  4. 3、按行读取文件内容
  5. 4、随机读取文件内容

  6. import java.io.BufferedReader;
  7. import java.io.File;
  8. import java.io.FileInputStream;
  9. import java.io.FileReader;
  10. import java.io.IOException;
  11. import java.io.InputStream;
  12. import java.io.InputStreamReader;
  13. import java.io.RandomAccessFile;
  14. import java.io.Reader;
  15. public class ReadFromFile {
  16. /**
  17.    * 以字节为单位读取文件,常用于读二进制文件,如图片、声音、影像等文件。
  18.    * @param fileName 文件的名
  19.    */
  20. public static void readFileByBytes(String fileName){
  21.    File file = new File(fileName);
  22.    InputStream in = null;
  23.    try {
  24.     System.out.println("以字节为单位读取文件内容,一次读一个字节:");
  25.     // 一次读一个字节
  26.     in = new FileInputStream(file);
  27.     int tempbyte;
  28.     while((tempbyte=in.read()) != -1){
  29.      System.out.write(tempbyte);
  30.     }
  31.     in.close();
  32.    } catch (IOException e) {
  33.     e.printStackTrace();
  34.     return;
  35.    }
  36.    try {
  37.     System.out.println("以字节为单位读取文件内容,一次读多个字节:");
  38.     //一次读多个字节
  39.     byte[] tempbytes = new byte[100];
  40.     int byteread = 0;
  41.     in = new FileInputStream(fileName);
  42.     ReadFromFile.showAvailableBytes(in);
  43.     //读入多个字节到字节数组中,byteread为一次读入的字节数
  44.     while ((byteread = in.read(tempbytes)) != -1){
  45.      System.out.write(tempbytes, 0, byteread);
  46.     }
  47.    } catch (Exception e1) {
  48.     e1.printStackTrace();
  49.    } finally {
  50.     if (in != null){
  51.      try {
  52.       in.close();
  53.      } catch (IOException e1) {
  54.      }
  55.     }
  56.    }
  57. }
  58. /**
  59.    * 以字符为单位读取文件,常用于读文本,数字等类型的文件
  60.    * @param fileName 文件名
  61.    */
  62. public static void readFileByChars(String fileName){
  63.    File file = new File(fileName);
  64.    Reader reader = null;
  65.    try {
  66.     System.out.println("以字符为单位读取文件内容,一次读一个字节:");
  67.     // 一次读一个字符
  68.     reader = new InputStreamReader(new FileInputStream(file));
  69.     int tempchar;
  70.     while ((tempchar = reader.read()) != -1){
  71.      //对于windows下,\r\n这两个字符在一起时,表示一个换行。
  72.      //但如果这两个字符分开显示时,会换两次行。
  73.      //因此,屏蔽掉\r,或者屏蔽\n。否则,将会多出很多空行。
  74.      if (((char)tempchar) != ''\r''){
  75.       System.out.print((char)tempchar);
  76.      }
  77.     }
  78.     reader.close();
  79.    } catch (Exception e) {
  80.     e.printStackTrace();
  81.    }
  82.    try {
  83.     System.out.println("以字符为单位读取文件内容,一次读多个字节:");
  84.     //一次读多个字符
  85.     char[] tempchars = new char[30];
  86.     int charread = 0;
  87.     reader = new InputStreamReader(new FileInputStream(fileName));
  88.     //读入多个字符到字符数组中,charread为一次读取字符数
  89.     while ((charread = reader.read(tempchars))!=-1){
  90.      //同样屏蔽掉\r不显示
  91.      if ((charread == tempchars.length)&&(tempchars[tempchars.length-1] != ''\r'')){
  92.       System.out.print(tempchars);
  93.      }else{
  94.       for (int i=0; i<charread; i++){
  95.        if(tempchars[i] == ''\r''){
  96.         continue;
  97.        }else{
  98.         System.out.print(tempchars[i]);
  99.        }
  100.       }
  101.      }
  102.     }
  103.    
  104.    } catch (Exception e1) {
  105.     e1.printStackTrace();
  106.    }finally {
  107.     if (reader != null){
  108.      try {
  109.       reader.close();
  110.      } catch (IOException e1) {
  111.      }
  112.     }
  113.    }
  114. }
  115. /**
  116.    * 以行为单位读取文件,常用于读面向行的格式化文件
  117.    * @param fileName 文件名
  118.    */
  119. public static void readFileByLines(String fileName){
  120.    File file = new File(fileName);
  121.    BufferedReader reader = null;
  122.    try {
  123.     System.out.println("以行为单位读取文件内容,一次读一整行:");
  124.     reader = new BufferedReader(new FileReader(file));
  125.     String tempString = null;
  126.     int line = 1;
  127.     //一次读入一行,直到读入null为文件结束
  128.     while ((tempString = reader.readLine()) != null){
  129.      //显示行号
  130.      System.out.println("line " + line + ": " + tempString);
  131.      line++;
  132.     }
  133.     reader.close();
  134.    } catch (IOException e) {
  135.     e.printStackTrace();
  136.    } finally {
  137.     if (reader != null){
  138.      try {
  139.       reader.close();
  140.      } catch (IOException e1) {
  141.      }
  142.     }
  143.    }
  144. }
  145. /**
  146.    * 随机读取文件内容
  147.    * @param fileName 文件名
  148.    */
  149. public static void readFileByRandomAccess(String fileName){
  150.    RandomAccessFile randomFile = null;
  151.    try {
  152.     System.out.println("随机读取一段文件内容:");
  153.     // 打开一个随机访问文件流,按只读方式
  154.     randomFile = new RandomAccessFile(fileName, "r");
  155.     // 文件长度,字节数
  156.     long fileLength = randomFile.length();
  157.     // 读文件的起始位置
  158.     int beginIndex = (fileLength > 4) ? 4 : 0;
  159.     //将读文件的开始位置移到beginIndex位置。
  160.     randomFile.seek(beginIndex);
  161.     byte[] bytes = new byte[10];
  162.     int byteread = 0;
  163.     //一次读10个字节,如果文件内容不足10个字节,则读剩下的字节。
  164.     //将一次读取的字节数赋给byteread
  165.     while ((byteread = randomFile.read(bytes)) != -1){
  166.      System.out.write(bytes, 0, byteread);
  167.     }
  168.    } catch (IOException e){
  169.     e.printStackTrace();
  170.    } finally {
  171.     if (randomFile != null){
  172.      try {
  173.       randomFile.close();
  174.      } catch (IOException e1) {
  175.      }
  176.     }
  177.    }
  178. }
  179. /**
  180.    * 显示输入流中还剩的字节数
  181.    * @param in
  182.    */
  183. private static void showAvailableBytes(InputStream in){
  184.    try {
  185.     System.out.println("当前字节输入流中的字节数为:" + in.available());
  186.    } catch (IOException e) {
  187.     e.printStackTrace();
  188.    }
  189. }

  190. public static void main(String[] args) {
  191.    String fileName = "C:/temp/newTemp.txt";
  192.    ReadFromFile.readFileByBytes(fileName);
  193.    ReadFromFile.readFileByChars(fileName);
  194.    ReadFromFile.readFileByLines(fileName);
  195.    ReadFromFile.readFileByRandomAccess(fileName);
  196. }
  197. }

  198.  

  199. 二、将内容追加到文件尾部

  200. import java.io.FileWriter;
  201. import java.io.IOException;
  202. import java.io.RandomAccessFile;

  203. /**
  204. * 将内容追加到文件尾部
  205. */
  206. public class AppendToFile {

  207. /**
  208.    * A方法追加文件:使用RandomAccessFile
  209.    * @param fileName 文件名
  210.    * @param content 追加的内容
  211.    */
  212. public static void appendMethodA(String fileName, String content){
  213.    try {
  214.     // 打开一个随机访问文件流,按读写方式
  215.     RandomAccessFile randomFile = new RandomAccessFile(fileName, "rw");
  216.     // 文件长度,字节数
  217.     long fileLength = randomFile.length();
  218.     //将写文件指针移到文件尾。
  219.     randomFile.seek(fileLength);
  220.     randomFile.writeBytes(content);
  221.     randomFile.close();
  222.    } catch (IOException e){
  223.     e.printStackTrace();
  224.    }
  225. }
  226. /**
  227.    * B方法追加文件:使用FileWriter
  228.    * @param fileName
  229.    * @param content
  230.    */
  231. public static void appendMethodB(String fileName, String content){
  232.    try {
  233.     //打开一个写文件器,构造函数中的第二个参数true表示以追加形式写文件
  234.     FileWriter writer = new FileWriter(fileName, true);
  235.     writer.write(content);
  236.     writer.close();
  237.    } catch (IOException e) {
  238.     e.printStackTrace();
  239.    }
  240. }

  241. public static void main(String[] args) {
  242.    String fileName = "C:/temp/newTemp.txt";
  243.    String content = "new append!";
  244.    //按方法A追加文件
  245.    AppendToFile.appendMethodA(fileName, content);
  246.    AppendToFile.appendMethodA(fileName, "append end. \n");
  247.    //显示文件内容
  248.    ReadFromFile.readFileByLines(fileName);
  249.    //按方法B追加文件
  250.    AppendToFile.appendMethodB(fileName, content);
  251.    AppendToFile.appendMethodB(fileName, "append end. \n");
  252.    //显示文件内容
  253.    ReadFromFile.readFileByLines(fileName);
  254. }
  255. }
  256. 三文件的各种操作类

  257. import java.io.*;

  258. /**
  259. * FileOperate.java
  260. * 文件的各种操作
  261. * @author 杨彩 http://blog.sina.com.cn/m/yangcai
  262. * 文件操作 1.0
  263. */

  264. public class FileOperate
  265. {

  266.    public FileOperate()
  267.    {
  268.    }
  269.    /**
  270.       * 新建目录
  271.       */
  272.    public void newFolder(String folderPath)
  273.    {
  274.        try
  275.        {
  276.            String filePath = folderPath;
  277.            filePath = filePath.toString();
  278.            File myFilePath = new File(filePath);
  279.            if(!myFilePath.exists())
  280.            {
  281.                myFilePath.mkdir();
  282.            }
  283.            System.out.println("新建目录操作 成功执行");
  284.        }
  285.        catch(Exception e)
  286.        {
  287.            System.out.println("新建目录操作出错");
  288.            e.printStackTrace();
  289.        }
  290.    }
  291.    /**
  292.       * 新建文件
  293.       */
  294.    public void newFile(String filePathAndName, String fileContent)
  295.    {
  296.        try
  297.        {
  298.            String filePath = filePathAndName;
  299.            filePath = filePath.toString();
  300.            File myFilePath = new File(filePath);
  301.            if (!myFilePath.exists())
  302.            {
  303.                myFilePath.createNewFile();
  304.            }
  305.            FileWriter resultFile = new FileWriter(myFilePath);
  306.            PrintWriter myFile = new PrintWriter(resultFile);
  307.            String strContent = fileContent;
  308.            myFile.println(strContent);
  309.            resultFile.close();
  310.            System.out.println("新建文件操作 成功执行");
  311.        }
  312.        catch (Exception e)
  313.        {
  314.            System.out.println("新建目录操作出错");
  315.            e.printStackTrace();
  316.        }
  317.    }
  318.    /**
  319.       * 删除文件
  320.       */
  321.    public void delFile(String filePathAndName)
  322.    {
  323.        try
  324.        {
  325.            String filePath = filePathAndName;
  326.            filePath = filePath.toString();
  327.            File myDelFile = new File(filePath);
  328.            myDelFile.delete();
  329.            System.out.println("删除文件操作 成功执行");
  330.        }
  331.        catch (Exception e)
  332.        {
  333.            System.out.println("删除文件操作出错");
  334.            e.printStackTrace();
  335.        }
  336.    }
  337.    /**
  338.       * 删除文件夹
  339.       */
  340.    public void delFolder(String folderPath)
  341.    {
  342.        try
  343.        {
  344.            delAllFile(folderPath); //删除完里面所有内容
  345.            String filePath = folderPath;
  346.            filePath = filePath.toString();
  347.            File myFilePath = new File(filePath);
  348.            if(myFilePath.delete()) { //删除空文件夹
  349.            System.out.println("删除文件夹" + folderPath + "操作 成功执行");
  350. } else {
  351.                System.out.println("删除文件夹" + folderPath + "操作 执行失败");
  352. }
  353.        }
  354.        catch (Exception e)
  355.        {
  356.            System.out.println("删除文件夹操作出错");
  357.            e.printStackTrace();
  358.        }
  359.    }
  360.    /**
  361.       * 删除文件夹里面的所有文件
  362.       * @param path String 文件夹路径 如 c:/fqf
  363.       */
  364.    public void delAllFile(String path)
  365.    {
  366.        File file = new File(path);
  367.        if(!file.exists())
  368.        {
  369.            return;
  370.        }
  371.        if(!file.isDirectory())
  372.        {
  373.            return;
  374.        }
  375.        String[] tempList = file.list();
  376.        File temp = null;
  377.        for (int i = 0; i < tempList.length; i++)
  378.        {
  379.            if(path.endsWith(File.separator))
  380.            {
  381.                temp = new File(path + tempList[i]);
  382.            }
  383.            else
  384.            {
  385.                temp = new File(path + File.separator + tempList[i]);
  386.            }
  387.            if (temp.isFile())
  388.            {
  389.                temp.delete();
  390.            }
  391.            if (temp.isDirectory())
  392.            {
  393.                //delAllFile(path+"/"+ tempList[i]);//先删除文件夹里面的文件
  394.                delFolder(path+ File.separatorChar + tempList[i]);//再删除空文件夹
  395.            }
  396.        }
  397.        System.out.println("删除文件操作 成功执行");
  398.    }
  399.    /**
  400.       * 复制单个文件
  401.       * @param oldPath String 原文件路径 如:c:/fqf.txt
  402.       * @param newPath String 复制后路径 如:f:/fqf.txt
  403.       */
  404.    public void copyFile(String oldPath, String newPath)
  405.    {
  406.        try
  407.        {
  408.            int bytesum = 0;
  409.            int byteread = 0;
  410.            File oldfile = new File(oldPath);
  411.            if (oldfile.exists())
  412.            {
  413.                //文件存在时
  414.                InputStream inStream = new FileInputStream(oldPath); //读入原文件
  415.                FileOutputStream fs = new FileOutputStream(newPath);
  416.                byte[] buffer = new byte[1444];
  417.                while ( (byteread = inStream.read(buffer)) != -1)
  418.                {
  419.                    bytesum += byteread; //字节数 文件大小
  420.                    System.out.println(bytesum);
  421.                    fs.write(buffer, 0, byteread);
  422.                }
  423.                inStream.close();
  424.            }
  425.            System.out.println("删除文件夹操作 成功执行");
  426.        }
  427.        catch (Exception e)
  428.        {
  429.            System.out.println("复制单个文件操作出错");
  430.            e.printStackTrace();
  431.        }
  432.    }
  433.    /**
  434.       * 复制整个文件夹内容
  435.       * @param oldPath String 原文件路径 如:c:/fqf
  436.       * @param newPath String 复制后路径 如:f:/fqf/ff
  437.       */
  438.    public void copyFolder(String oldPath, String newPath)
  439.    {
  440.        try
  441.        {
  442.            (new File(newPath)).mkdirs(); //如果文件夹不存在 则建立新文件夹
  443.            File a=new File(oldPath);
  444.            String[] file=a.list();
  445.            File temp=null;
  446.            for (int i = 0; i < file.length; i++)
  447.            {
  448.                if(oldPath.endsWith(File.separator))
  449.                {
  450.                    temp=new File(oldPath+file[i]);
  451.                }
  452.                else
  453.                {
  454.                    temp=new File(oldPath+File.separator+file[i]);
  455.                }
  456.                if(temp.isFile())
  457.                {
  458.                    FileInputStream input = new FileInputStream(temp);
  459.                    FileOutputStream output = new FileOutputStream(newPath + "/" +
  460.                    (temp.getName()).toString());
  461.                    byte[] b = new byte[1024 * 5];
  462.                    int len;
  463.                    while ( (len = input.read(b)) != -1)
  464.                    {
  465.                        output.write(b, 0, len);
  466.                    }
  467.                    output.flush();
  468.                    output.close();
  469.                    input.close();
  470.                }
  471.                if(temp.isDirectory())
  472.                {
  473.                    //如果是子文件夹
  474.                    copyFolder(oldPath+"/"+file[i],newPath+"/"+file[i]);
  475.                }
  476.            }
  477.            System.out.println("复制文件夹操作 成功执行");
  478.        }
  479.        catch (Exception e)
  480.        {
  481.            System.out.println("复制整个文件夹内容操作出错");
  482.            e.printStackTrace();
  483.        }
  484.    }
  485.    /**
  486.       * 移动文件到指定目录
  487.       * @param oldPath String 如:c:/fqf.txt
  488.       * @param newPath String 如:d:/fqf.txt
  489.       */
  490.    public void moveFile(String oldPath, String newPath)
  491.    {
  492.        copyFile(oldPath, newPath);
  493.        delFile(oldPath);
  494.    }
  495.    /**
  496.       * 移动文件到指定目录
  497.       * @param oldPath String 如:c:/fqf.txt
  498.       * @param newPath String 如:d:/fqf.txt
  499.       */
  500.    public void moveFolder(String oldPath, String newPath)
  501.    {
  502.        copyFolder(oldPath, newPath);
  503.        delFolder(oldPath);
  504.    }
  505.    public static void main(String args[])
  506.    {
  507.        String aa,bb;
  508.        boolean exitnow=false;
  509.        System.out.println("使用此功能请按[1] 功能一:新建目录");
  510.        System.out.println("使用此功能请按[2] 功能二:新建文件");
  511.        System.out.println("使用此功能请按[3] 功能三:删除文件");
  512.        System.out.println("使用此功能请按[4] 功能四:删除文件夹");
  513.        System.out.println("使用此功能请按[5] 功能五:删除文件夹里面的所有文件");
  514.        System.out.println("使用此功能请按[6] 功能六:复制文件");
  515.        System.out.println("使用此功能请按[7] 功能七:复制文件夹的所有内容");
  516.        System.out.println("使用此功能请按[8] 功能八:移动文件到指定目录");
  517.        System.out.println("使用此功能请按[9] 功能九:移动文件夹到指定目录");
  518.        System.out.println("使用此功能请按[10] 退出程序");
  519.        while(!exitnow)
  520.        {
  521.            FileOperate fo=new FileOperate();
  522.            try
  523.            {
  524.                BufferedReader Bin=new BufferedReader(new InputStreamReader(System.in));
  525.                String a=Bin.readLine();
  526.                int b=Integer.parseInt(a);
  527.                switch(b)
  528.                {
  529.                    case 1:System.out.println("你选择了功能一 请输入目录名");
  530.                    aa=Bin.readLine();
  531.                    fo.newFolder(aa);
  532.                    break;
  533.                    case 2:System.out.println("你选择了功能二 请输入文件名");
  534.                    aa=Bin.readLine();
  535.                    System.out.println("请输入在"+aa+"中的内容");
  536.                    bb=Bin.readLine();
  537.                    fo.newFile(aa,bb);
  538.                    break;
  539.                    case 3:System.out.println("你选择了功能三 请输入文件名");
  540.                    aa=Bin.readLine();
  541.                    fo.delFile(aa);
  542.                    break;
  543.                    case 4:System.out.println("你选择了功能四 请输入文件名");
  544.                    aa=Bin.readLine();
  545.                    fo.delFolder(aa);
  546.                    break;
  547.                    case 5:System.out.println("你选择了功能五 请输入文件名");
  548.                    aa=Bin.readLine();
  549.                    fo.delAllFile(aa);
  550.                    break;
  551.                    case 6:System.out.println("你选择了功能六 请输入文件名");
  552.                    aa=Bin.readLine();
  553.                    System.out.println("请输入目标文件名");
  554.                    bb=Bin.readLine();
  555.                    fo.copyFile(aa,bb);
  556.                    break;
  557.                    case 7:System.out.println("你选择了功能七 请输入源文件名");
  558.                    aa=Bin.readLine();
  559.                    System.out.println("请输入目标文件名");
  560.                    bb=Bin.readLine();
  561.                    fo.copyFolder(aa,bb);
  562.                    break;
  563.                    case 8:System.out.println("你选择了功能八 请输入源文件名");
  564.                    aa=Bin.readLine();
  565.                    System.out.println("请输入目标文件名");
  566.                    bb=Bin.readLine();
  567.                    fo.moveFile(aa,bb);
  568.                    break;
  569.                    case 9:System.out.println("你选择了功能九 请输入源文件名");
  570.                    aa=Bin.readLine();
  571.                    System.out.println("请输入目标文件名");
  572.                    bb=Bin.readLine();
  573.                    fo.moveFolder(aa,bb);
  574.                    break;
  575.                    case 10:exitnow=true;
  576.                    System.out.println("程序结束,请退出");
  577.                    break;
  578.                    default:System.out.println("输入错误.请输入1-10之间的数");
  579.                }
  580.                System.out.println("请重新选择功能");
  581.            }
  582.            catch(Exception e)
  583.            {
  584.                System.out.println("输入错误字符或程序出错");
  585.            }
  586.        }
  587.    }
  588. }


  589. 在这里特别感谢作者张涛.


  590. 文章出处:http:

阅读(3573) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~