java文件读写操作大全

转自http://blog.sina.com.cn/s/blog_4a9f789a0100ik3p.html

一.获得控制台用户输入的信息

 

 1      public String getInputMessage() throws IOException...{
 2          System.out.println("请输入您的命令∶");
 3          byte buffer[]=new byte[1024];
 4          int count=System.in.read(buffer);
 5          char[] ch=new char[count-2];//最后两位为结束符,删去不要
 6          for(int i=0;i<count-2;i++)
 7              ch[i]=(char)buffer[i];
 8          String str=new String(ch);
 9          return str;
10      }

 

     可以返回用户输入的信息,不足之处在于不支持中文输入,有待进一步改进。

 

     二.复制文件      1.以文件流的方式复制文件

 

 1   public void copyFile(String src,String dest) throws IOException...{
 2          FileInputStream in=new FileInputStream(src);
 3          File file=new File(dest);
 4          if(!file.exists())
 5              file.createNewFile();
 6          FileOutputStream out=new FileOutputStream(file);
 7          int c;
 8          byte buffer[]=new byte[1024];
 9          while((c=in.read(buffer))!=-1)...{
10              for(int i=0;i<c;i++)
11                  out.write(buffer[i]);        
12          }
13          in.close();
14          out.close();
15      }

 

     该方法经过测试,支持中文处理,并且可以复制多种类型,比如txt,xml,jpg,doc等多种格式

 

     三.写文件

 

     1.利用PrintStream写文件

 

 1   public void PrintStreamDemo()...{
 2          try ...{
 3              FileOutputStream out=new FileOutputStream("D:/test.txt");
 4              PrintStream p=new PrintStream(out);
 5              for(int i=0;i<10;i++)
 6                  p.println("This is "+i+" line");
 7          } catch (FileNotFoundException e) ...{
 8              e.printStackTrace();
 9          }
10      }

 2.利用StringBuffer写文件

 1 public void StringBufferDemo() throws IOException......{
 2          File file=new File("/root/sms.log");
 3          if(!file.exists())
 4              file.createNewFile();
 5          FileOutputStream out=new FileOutputStream(file,true);        
 6          for(int i=0;i<10000;i++)......{
 7              StringBuffer sb=new StringBuffer();
 8              sb.append("这是第"+i+"行:前面介绍的各种方法都不关用,为什么总是奇怪的问题 ");
 9              out.write(sb.toString().getBytes("utf-8"));
10          }        
11          out.close();
12      }

     该方法可以设定使用何种编码,有效解决中文问题。
四.文件重命名

 

 1      public void renameFile(String path,String oldname,String newname)...{
 2          if(!oldname.equals(newname))...{//新的文件名和以前文件名不同时,才有必要进行重命名
 3              File oldfile=new File(path+"/"+oldname);
 4              File newfile=new File(path+"/"+newname);
 5              if(newfile.exists())//若在该目录下已经有一个文件和新文件名相同,则不允许重命名
 6                  System.out.println(newname+"已经存在!");
 7              else...{
 8                  oldfile.renameTo(newfile);
 9              }
10          }         
11      }

  五.转移文件目录
     转移文件目录不等同于复制文件,复制文件是复制后两个目录都存在该文件,而转移文件目录则是转移后,只有新目录中存在该文件。

 1      public void changeDirectory(String filename,String oldpath,String newpath,boolean cover)...{
 2          if(!oldpath.equals(newpath))...{
 3              File oldfile=new File(oldpath+"/"+filename);
 4              File newfile=new File(newpath+"/"+filename);
 5              if(newfile.exists())...{//若在待转移目录下,已经存在待转移文件
 6                  if(cover)//覆盖
 7                      oldfile.renameTo(newfile);
 8                  else
 9                      System.out.println("在新目录下已经存在:"+filename);
10              }
11              else...{
12                  oldfile.renameTo(newfile);
13              }
14          }       
15      }

     六.读文件
     1.利用FileInputStream读取文件

 

 1     public String FileInputStreamDemo(String path) throws IOException...{
 2          File file=new File(path);
 3          if(!file.exists()||file.isDirectory())
 4              throw new FileNotFoundException();
 5          FileInputStream fis=new FileInputStream(file);
 6          byte[] buf = new byte[1024];
 7          StringBuffer sb=new StringBuffer();
 8          while((fis.read(buf))!=-1)...{
 9              sb.append(new String(buf));    
10              buf=new byte[1024];//重新生成,避免和上次读取的数据重复
11          }
12          return sb.toString();
13      }

 

2.利用BufferedReader读取

 

     在IO操作,利用BufferedReader和BufferedWriter效率会更高一点

 

 1    public String BufferedReaderDemo(String path) throws IOException...{
 2          File file=new File(path);
 3          if(!file.exists()||file.isDirectory())
 4              throw new FileNotFoundException();
 5          BufferedReader br=new BufferedReader(new FileReader(file));
 6          String temp=null;
 7          StringBuffer sb=new StringBuffer();
 8          temp=br.readLine();
 9          while(temp!=null)...{
10              sb.append(temp+" ");
11              temp=br.readLine();
12          }
13          return sb.toString();
14      }

     3.利用dom4j读取xml文件

  public Document readXml(String path) throws DocumentException, IOException...{File file=new File(path);BufferedReader bufferedreader = new BufferedReader(new FileReader(file));SAXReader saxreader = new SAXReader();Document document = (Document)saxreader.read(bufferedreader);bufferedreader.close();return document;}

 

     七.创建文件(文件夹)

 

 1 1.创建文件夹  
 2      public void createDir(String path)...{
 3          File dir=new File(path);
 4          if(!dir.exists())
 5              dir.mkdir();
 6      }
 7 2.创建新文件
 8      public void createFile(String path,String filename) throws IOException...{
 9          File file=new File(path+"/"+filename);
10          if(!file.exists())
11              file.createNewFile();
12      }

  八.删除文件(目录)

 1 1.删除文件     
 2      public void delFile(String path,String filename)...{
 3          File file=new File(path+"/"+filename);
 4          if(file.exists()&&file.isFile())
 5              file.delete();
 6      }
 7 2.删除目录
 8 要利用File类的delete()方法删除目录时,必须保证该目录下没有文件或者子目录,否则删除失败,因此在实际应用中,我们要删除目录,必须利用递归删除该目录下的所有子目录和文件,然后再删除该目录。  
 9      public void delDir(String path)...{
10          File dir=new File(path);
11          if(dir.exists())...{
12              File[] tmp=dir.listFiles();
13              for(int i=0;i<tmp.length;i++)...{
14                  if(tmp[i].isDirectory())...{
15                      delDir(path+"/"+tmp[i].getName());
16                  }
17                  else...{
18                      tmp[i].delete();
19                  }
20              }
21              dir.delete();
22          }
23      }

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

转载于:https://www.cnblogs.com/woqunimeidebokedizhi/archive/2013/05/03/3056277.html

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/421816.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

(Java)Integer类的其他常用方法

package com.book.lite;/*** author zhangyu* date 2021年08月15日 8:01 下午* Integer类&#xff0c;其他常用方法&#xff1a;* 1.parseInt(String i) 将数字格式字符串&#xff0c;转换成基本数据类型* 2.parseInt(String i, int radix) 将数字类型字符串转换成进制数* 3.t…

libev源码分析--常用的watcher

在上一篇文章里&#xff0c;我们分析了libev整体设计思想和主循环的工作原理&#xff0c;也提到了watcher是衔接开发者代码的主要入口。watcher与开发者最接近&#xff0c;也与具体事件处理逻辑最接近。所以&#xff0c;watcher的具体实现&#xff0c;与性能的关系也相当密切。…

(Java)Character类

package com.book.lite;import sun.lwawt.macosx.CSystemTray;import java.util.Scanner;/*** author zhangyu* date 2021年08月16日 10:50 下午* Character类的方法* 1.判断是否小写&#xff1a;isLowerCase()* 2.判断是否大写&#xff1a;isUpperCase()* 3.判断是不是数字&am…

棋盘切割 DP POJ 1191

把方差公式先变形为 σ2 (1/n)∑xi2-xa2 xa为平均值。 由于要求标准差最小&#xff0c;只需方差最小&#xff0c;平均值都是一样的&#xff0c;n也是一样的&#xff0c;这样原问题就变为求这n快小棋盘总分的平方和最小 考虑左上角为&#xff08;x1,y1&#xff09;,右上角为&am…

lucene,lucene.net学习教程

lucene学习教程 1.1 什么是lucene Lucene是一个全文搜索框架&#xff0c;而不是应用产品。因此它并不像www.baidu.com 或者google Desktop那么拿来就能用&#xff0c;它只是提供了一种工具让你能实现这些产品。 2 lucene的工作方式 lucene提供的服务实际包含两部分&#xf…

(JAVA)正则表达式

正则表达式的常见规则 1.字符类[abc]&#xff1a;字符必须是abc其中一个[a-z]&#xff1a;字符必须是小写字母[A-Z]&#xff1a;字符必须是大写字母[a-zA-Z]&#xff1a;字符必须是字母[^abc]&#xff1a;字符不能是abc其中一个[^a-z]&#xff1a;字符不能是小写字母[^a-zA-Z]:…

巧用“傍术”选择陈列点

割箱 陈列 是一种将包装纸箱割斜角&#xff0c;以露出商品的 陈列 方式&#xff0c;广泛应用在包袋食品及小百货商品。  商超内的位置很多&#xff0c;选择什么样的位置 陈列 产品能够起到最好的效果呢&#xff1f;  首先是要找视觉效果尽可能好的地方。消费者进入商场第一…

(JAVA) * 使用正则表达式,给字符串排序 * 使用数组排序

package com.book.lite;import java.util.Arrays;/*** author zhangyu* date 2021年08月19日 10:49 下午* 使用正则表达式&#xff0c;给字符串排序* 使用数组排序*/ public class RegexDemo1 {public static void main(String[] args) {test();}public static void test(){Str…

python 使用 pip 安装第三方库 导入不成功

本文是什么意思呢&#xff1f; 就是你需要使用一些库安装老师或者网上说的 通过pip 安装下载了第三方库&#xff0c;但是使用 import xxx from xxx import xx &#xff0c;pycharm ide 导入的下面还有红色波浪线&#xff0c;导入不成功。 这是什么原因&#xff1f; 这是pyc…

LLVM每日谈之十三 使用LLVM自带的PASS

作者&#xff1a;snsn1984 PS&#xff1a;最近一段时间&#xff0c;投入在LLVM上的时间有些减少。差点把对它的研究断掉&#xff0c;今天开始继续。对LLVM的研究需要很长一段时间的坚持不懈才可以彻底搞明白。 前面已经介绍过如何写自己的PASS&#xff0c;并且也针对一个简单的…

(JAVA)Math类

package com.book.lite;import java.util.regex.Matcher;/*** author zhangyu* date 2021年08月19日 11:34 下午* 1.绝对值*/ public class MathDemo {public static void main(String[] args) {System.out.println(methon_1());System.out.println(methon_2());System.out.pri…

Android学习笔记-判断手机外部存储是否可读写

通过调用Environment的getExternalStorageState()方法来判断外部存储的状态: /* 查检外部存储读取与写入功能是否可用 */ public boolean isExternalStorageWritable() {String state Environment.getExternalStorageState();if (Environment.MEDIA_MOUNTED.equals(state)) {r…

寄存器指令MIPS 寄存器介绍

之前朋友几篇文章介绍了改寄存器指令的文章. 关联文章的地址 MIPS有32个通用寄存器&#xff08;$0-$31&#xff09;&#xff0c;各寄存器的功能及汇编程序中应用约定如下&#xff1a; 下表描述32个通用寄存器的别名和用处 REGISTER NAME USAGE $0 $zero 常量0(constant va…

(JAVA)Random类

package com.book.lite;import java.util.Random;/*** author zhangyu* date 2021年08月19日 11:57 下午* Math.random()获取随机数&#xff0c;底层调用Random类* Random类* 1.构造方法* 2.nextInt(int n )*/public class RandomDemo {public static void main(String[] args)…