import java.io.*;


/**
 * 
 * 功能描述:创建TXT文件并进行读、写、修改操作
 *      
 * @author <a href="mailto:zhanghhui@126.com">KenZhang</a>
 * @version 1.0 
 * Creation date: 2007-12-18 - 下午06:48:45
 */
public class ReadWriteFile {
    public static BufferedReader bufread;
    //指定文件路径和名称
    private static String path = "D:/suncity.txt";
    private static  File filename = new File(path);
    private static String readStr ="";


    /**
     * 创建文本文件.
     * @throws IOException 
     * 
     */
    public static void creatTxtFile() throws IOException{
        if (!filename.exists()) {
            filename.createNewFile();
            System.err.println(filename + "已创建!");
        }
    }
    
    /**
     * 读取文本文件.
     * 
     */
    public static String readTxtFile(){
        String read;
        FileReader fileread;
        try {
            fileread = new FileReader(filename);
            bufread = new BufferedReader(fileread);
            try {
                while ((read = bufread.readLine()) != null) {
                    readStr = readStr + read+ "\r\n";
                }
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        } catch (FileNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        System.out.println("文件内容是:"+ "\r\n" + readStr);
        return readStr;
    }
    
    /**
     * 写文件.
     * 
     */
    public static void writeTxtFile(String newStr) throws IOException{
        //先读取原有文件内容,然后进行写入操作
        String filein = newStr + "\r\n" + readStr + "\r\n";
        RandomAccessFile mm = null;
        try {
            mm = new RandomAccessFile(filename, "rw");
            mm.writeBytes(filein);
        } catch (IOException e1) {
            // TODO 自动生成 catch 块
            e1.printStackTrace();
        } finally {
            if (mm != null) {
                try {
                    mm.close();
                } catch (IOException e2) {
                    // TODO 自动生成 catch 块
                    e2.printStackTrace();
                }
            }
        }
    }
    
    /**
     * 将文件中指定内容的第一行替换为其它内容.
     * 
     * @param oldStr
     *            查找内容
     * @param replaceStr
     *            替换内容
     */
    public static void replaceTxtByStr(String oldStr,String replaceStr) {
        String temp = "";
        try {
            File file = new File(path);
            FileInputStream fis = new FileInputStream(file);
            InputStreamReader isr = new InputStreamReader(fis);
            BufferedReader br = new BufferedReader(isr);
            StringBuffer buf = new StringBuffer();

            // 保存该行前面的内容
; (temp = br.readLine()) != null
                    && !temp.equals(oldStr); j++) {
                buf = buf.append(temp);
                buf = buf.append(System.getProperty("line.separator"));
            }

            // 将内容插入
            buf = buf.append(replaceStr);

            // 保存该行后面的内容
            while ((temp = br.readLine()) != null) {
                buf = buf.append(System.getProperty("line.separator"));
                buf = buf.append(temp);
            }

            br.close();
            FileOutputStream fos = new FileOutputStream(file);
            PrintWriter pw = new PrintWriter(fos);
            pw.write(buf.toString().toCharArray());
            pw.flush();
            pw.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    /**
     * main方法测试
     * @param s
     * @throws IOException
     */
    public static void main(String[] s) throws IOException {
        ReadWriteFile.creatTxtFile();
        ReadWriteFile.readTxtFile();
        ReadWriteFile.writeTxtFile("20080808:12:13");
//        ReadWriteFile.replaceTxtByStr("ken", "zhang");
    }
}

修改单个文件字符串

String s="";
            try{
                   FileInputStream fis=new FileInputStream("/home/liu_yin/Android/apktool1.5.2/javatest");//从d:\\1\\3.txt");读出内容到s
                   byte[]b=new byte[1024];
                  
                   while(true){
                       int i=fis.read(b);
                       if(i==-1)break;
                       s=s+new String(b,0,i);
                   }
                   fis.close();
                }catch(Exception e){
                    e.printStackTrace();
                }
                s=s.replaceAll("LogUtil", "//LogUtil");//,进行替换我开始以为是 换行呢,不会还百度了。要换行"\r\n"
                
                try{
                    FileOutputStream fos=new FileOutputStream("/home/liu_yin/Android/apktool1.5.2/javatest",false);//true原有续写,false是追加。如果源文件不存在就新建了
                    fos.write(s.getBytes());
                    fos.close();
                }catch(Exception e){
                    e.printStackTrace();
                }

遍历文件夹下的所有文件

static void getFiles(String filePath){
  File root = new File(filePath);
    File[] files = root.listFiles();
    for(File file:files){    
     if(file.isDirectory()){
      /*
       * 递归调用
       */
      getFiles(file.getAbsolutePath());
      filelist.add(file.getAbsolutePath());
      System.out.println("显示"+filePath+"下所有子目录及其文件"+file.getAbsolutePath());
     }else{
      System.out.println("显示"+filePath+"下所有子目录"+file.getAbsolutePath());
     }    
    }
 }


java创建TXT文件并进行读、写、修改操作的更多相关文章

  1. JAVA 创建TXT文件,写入文件内容,读取文件内容

    [java]  view plain copy   package com.abin.facade.ws.mail.function; import java.io.BufferedReader; i ...

  2. Java创建TXT文件并写入 内容

    public static void main(String[] args) { String filePath = "E:/" + "1.txt"; Stri ...

  3. Java读写txt文件

    1.Java读取txt文件 1.1.使用FileInputStream: public static String readFile(File file, String charset){ //设置默 ...

  4. java 读取TXT文件的方法

    java读取txt文件内容.可以作如下理解: 首先获得一个文件句柄.File file = new File(); file即为文件句柄.两人之间连通电话网络了.接下来可以开始打电话了. 通过这条线路 ...

  5. java读取TXT文件的方法

    java读取txt文件内容.可以作如下理解: 首先获得一个文件句柄.File file = new File(); file即为文件句柄.两人之间连通电话网络了.接下来可以开始打电话了. 通过这条线路 ...

  6. java读取txt文件内容

    package read; import java.io.BufferedReader; import java.io.File; import java.io.FileReader; public ...

  7. Java读取txt文件信息并操作。

    一.java读取txt文件内容 import java.io.BufferedInputStream; import java.io.BufferedReader; import java.io.Fi ...

  8. JAVA获取txt文件内容

    JAVA 读取txt文件内容 通常,我们可以直接通过文件流来读取txt文件的内容,但有时可能会出现乱码!此时只要设置一下文件字符编码即可. public class txttest { /** * 读 ...

  9. Java读取txt文件、excel文件的方法

    Java读取txt文件.excel文件的方法 1.读取txt文件 public static String getFileContent(String filePath,String charset) ...

随机推荐

  1. 移动端base.css

    html { color: #333; /*规定主色调,依据业务场景(非必须)*/ background: #F6F6F6; /*规定主背景,依据业务场景(非必须)*/ overflow-y: aut ...

  2. BZOJ4145 [AMPPZ2014]The Prices

    题意 你要购买m种物品各一件,一共有n家商店,你到第i家商店的路费为d[i],在第i家商店购买第j种物品的费用为c[i][j],求最小总费用. \(n \leq 100,m \leq 16\) 分析 ...

  3. ballerina 学习四 如何进行项目结构规划

    备注: *   ballerina 程序员可以将代码放到一个文件或者一个项目目录 *   一个ballerina program是一个已经编译以及链接的二进制文件 *   package是一个包含ba ...

  4. 基于jquery 的ajax 文件下载

    ajax 文件下载,实际上就是模拟表单提交,代码如下: function download(url, data, method){ //url and data options required if ...

  5. IMP-00013: 只有 DBA 才能导入由其他 DBA 导出的文件

    IMP-00013: only a DBA can import a file exported by another DBA 处理方法:在给目标环境的用户赋予dba权限,或者细粒度一些,赋予imp_ ...

  6. beego的配置文件记录

    摘自https://github.com/beego/tutorial/blob/master/zh/3/params.slide * beego的默认参数 - AppName 应用名称,默认是 be ...

  7. Django 的ORM

    指定字段: <1> CharField:字符串字段,用于较短的字符串,CharField 要求必须有一个参数 maxlength,用于从数据库层和Django效验层限制该字段所允许的最大字 ...

  8. SQL 只取重复记录一条记录并且是最小值

    and not exists( and a.StateValue>StateValue ) '

  9. DynamicConverter

    folly/DynamicConverter.h When dynamic objects contain data of a known type, it is sometimes useful t ...

  10. 关于alter database open resetlogs及incarnation的一点理解

    关于alter database open resetlogs及incarnation的一点理解 不完全恢复只能做一次吗? 采用rman的默认设置,对数据库进行了backup database备份,进 ...