java 操作本地文件

1、写本地文件

/**
 * 
 * @param sDestFile 文件名
 * @param sContent  内容
 *  autho whh
 */
    public static void appendToFile(String sDestFile, String sContent) {
    // String sContent = "I love Ysm";
    // String sDestFile = "F:/work/logParse/autoCreateHql/myWrite.txt";
    File destFile = new File(sDestFile);
    BufferedWriter out = null;
    if (!destFile.exists()) {
        try {
            destFile.createNewFile();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    try {
        out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(sDestFile, true)));
        out.write(sContent);
        out.newLine();
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        try {
            if (out != null) {
                out.close();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

2、找出所有以某个字符串结尾的文件名的文件

public static void findFile(File file) {
//1.首先判断传入的路径是否存在
        if (file.exists()) {

            // 2.如果是文件,判断是不是以java结尾

            if (file.isFile()) {
                String filePath = file.getPath();
                if (file.getPath().endsWith("createtable.sh")) { //此处限定以"createtable.sh"结尾
                    appendToFile("G:\\work\\compareHiveMetaToTreasury\\createtableFileName",filePath);
                   // System.out.println(filePath);
                }
            }
            // 3如果给的是文件夹   需要递归调用
            if (file.isDirectory()) {
                File[] otherFile = file.listFiles();
                for (File f : otherFile) {
                    findFile(f);// 通过递归调用
                }
            }
        } else {
            System.out.println("您给定的文件夹不存在");
        }
    }

猜你喜欢

转载自my.oschina.net/u/3267050/blog/1806163