java如何把多段内容分别写入到不同的txt文本中

如题所述

java将多段内容分别写入不同的txt文件中

public class FileStreamDemo {

    public static void main(String[] args) {
        // å£°æ˜Žå¤šè¡Œå†…容
        String multiText = "行1\n" +
                "行2\n" +
                "行3\n" +
                "行4\n" +
                "行5\n" +
                "\n" +
                "\n" +
                "行6";


        BufferedReader bReader = new BufferedReader(new StringReader(multiText));
        String lineStr = null;
        try {
            int index = 0;
            while ((lineStr = bReader.readLine()) != null) {
                if (index == 3) {
                    index = 0;
                }

                writeFile(new File("file", "content_" + index + ".txt"), lineStr);

                index++;
            }
            System.out.println("写入成功");
        } catch (Exception e) {
            e.printStackTrace();
            System.out.println("写入失败:" + e.getMessage());
        }


    }


    /**
     * å†™å…¥æ–‡æœ¬å†…容到文件中
     *
     * @param file    å†™å…¥çš„文件路径和文件名
     * @param content å†™å…¥çš„内容
     */
    private static void writeFile(File file, String content) throws IOException {
        // æœ¬åœ°å¦‚果不存在,创建一个
        if (!file.exists()) {
            File parentPath = file.getParentFile();
            parentPath.mkdirs();  // åˆ›å»ºç›®å½•
            file.createNewFile();  // åˆ›å»ºæ–‡ä»¶
        }

        System.out.println("准备写入文件:" + file.getAbsolutePath());

        FileOutputStream fos = new FileOutputStream(file, true);
        BufferedWriter bWriter = new BufferedWriter(new OutputStreamWriter(fos));
        bWriter.write(content);
        bWriter.write("\n");

        bWriter.flush();
        bWriter.close();
    }
}
温馨提示:答案为网友推荐,仅供参考
相似回答