for(int i=1i<=60i++)
File file = new File("filen"+i+"拿橘.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()
}
}
代码如下:
import java.io.BufferedReaderimport java.io.BufferedWriter
import java.io.File
import java.io.FileInputStream
import 橡凳java.io.FileNotFoundException
import java.io.FileOutputStream
import java.io.IOException
import java.io.InputStreamReader
import java.io.OutputStreamWriter
public 梁毕旅class App {
public static void main(String[] args) throws FileNotFoundException, IOException {
try (
FileInputStream inputStream = new FileInputStream(new File("d:\\temp\\abc.txt"))
InputStreamReader streamReader = new InputStreamReader(inputStream)
BufferedReader reader = new BufferedReader(streamReader)
FileOutputStream outputStream = new FileOutputStream(new File("d:\\temp\\output.txt"))
OutputStreamWriter streamWriter = new OutputStreamWriter(outputStream)
BufferedWriter writer = new BufferedWriter(streamWriter)
) {
int count = 1
String line = null
while ((line = reader.readLine()) != null) {
writer.write(count++ + ": " 数含+ line)
writer.newLine()
}
}
System.out.println("done.")
}
}
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)