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();
}
}