1. 程式人生 > >java檔案替換寫法

java檔案替換寫法

 @Test
    public void we1() throws Exception {

        FileReader fileReader = new FileReader("a.txt");
        FileWriter fileWriter = new FileWriter("ss.txt");

        File src = new File("H:/test.txt");
        String cont = Monitoring.readfileconten("H:/test.txt");
        System.out.println(cont);
        //對得到的內容進行處理
        cont = cont.replaceAll("aaa", "bbb");
        System.out.println(cont);
        //更新原始檔
        System.out.println(Monitoring.write(cont, src));

    }

    public static String readfileconten(String path) {
        File file = new File(path);
        StringBuffer stringBuffer = new StringBuffer();
        String lin = null;
        try {
            BufferedReader bufferedReader = new BufferedReader(new FileReader(file));
            while ((lin = bufferedReader.readLine()) != null) {
                stringBuffer.append(lin + "\n");
            }
            bufferedReader.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return stringBuffer.toString();
    }

    public static boolean write(String cont, File dist) {
        try {
            BufferedWriter writer = new BufferedWriter(new FileWriter(dist));
            writer.write(cont);
            writer.flush();
            writer.close();
            return true;
        } catch (IOException e) {
            e.printStackTrace();
            return false;
        }

    }