IO流文件目录读写,修改


    /**
     * @param sourcePath 源文件路径
     * @param newPath    目标文件路径
     * @throws IOException
     */
    public static void copyDir(String sourcePath, String newPath) throws IOException {
        File file = new File(sourcePath);
        String[] filePath = file.list();

        if (!(new File(newPath)).exists()) {
            (new File(newPath)).mkdir();
        }

        for (int i = 0; i < filePath.length; i++) {
            if ((new File(sourcePath + file.separator + filePath[i])).isDirectory()) {
                copyDir(sourcePath + file.separator + filePath[i], newPath + file.separator + filePath[i]);
            }

            if (new File(sourcePath + file.separator + filePath[i]).isFile()) {
                copyFile(sourcePath + file.separator + filePath[i], newPath + file.separator + filePath[i]);
            }

        }
    }

    /**
     * 复制文件
     *
     * @param oldPath
     * @param newPath
     * @throws IOException
     */
    public static void copyFile(String oldPath, String newPath) throws IOException {
        File oldFile = new File(oldPath);
        File file = new File(newPath);
        String line = null;
        BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(oldFile)));
        PrintWriter pw = new PrintWriter(file); 

        while ((line = br.readLine()) != null) {
                        /*    TODO
                            还可以在这里修改读取的文件内容,如将某行修改成 line = "abc" ;
                         */
            pw.write(line);
            //换行的话用 pw.println(line);
        }
        pw.flush();
        br.close();
        pw.flush();
    }

    @Test
    public void copyFileTest() {
        String sourcePath = "F:\\baseFramework\\";
        //复制到的位置
        String topathname = "E:\\baseFramework";
        try {
            copyDir(sourcePath, topathname);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

在TODO这里可以将读取到的某个文件中的某一行进行修改,例如:假如a.txt文件中有一行是这样的 ''我欲乘风归去' 如下图所示:

a.txt

这里就可以做判断如:
 

if(line.contains("我欲乘风归去")){
    line = "水调歌头·明月几时有";
}

这样就可以修改在读取的a.txt文件了,也可以用正则修改该行.

猜你喜欢

转载自blog.csdn.net/qq_22899021/article/details/82423678