学习了朋友的代码,千辛万苦终于写完了 继续加油
写的一个复制测试类代码
主要收获:
1.在同一个循环内可以对输入输出流进行关闭打开
2.以及 new FileWriter(File xxx) 可以创建不同的对象
3.面向对象在代码中的体现 当然我这是简化的 懒得抽一个类出来了 将就一下
完整代码
写的一个复制测试类代码
主要收获:
1.在同一个循环内可以对输入输出流进行关闭打开
2.以及 new FileWriter(File xxx) 可以创建不同的对象
3.面向对象在代码中的体现 当然我这是简化的 懒得抽一个类出来了 将就一下
while (i++ < count) { content += br2.readLine(); content += "\r\n"; BufferedWriter bw3 = new BufferedWriter( new FileWriter(toFile + " " + "-" + " " + "副标" + " " + "(" + a + ")" + ".txt")); //方便对照最终文件的数目 System.out.println("i is:" + i); a++; bw3.write(content); bw3.flush(); bw3.close(); }
public static void main(String[] args) { new Test2().startMain("D://music.txt", "D://copy.txt"); }
完整代码
package com.yellow.homework;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
public class Test2 {
/**
* @param args
*/
public static void main(String[] args) {
new Test2().startMain("D://music.txt", "D://copy.txt");
}
public static void startMain(String fromFilePath, String toFilePath) {
System.out.println(fromFilePath);
// 创建歌词文本
File fromFile = new File(fromFilePath);
if (!fromFile.exists()) {
System.out.println("请先创建歌词文本");
return;
}
// 创建第一个文本
File toFile = new File(toFilePath);
if (!toFile.exists()) {
try {
boolean newCopy = toFile.createNewFile();
if (newCopy) {
System.out.println("文本创建成功");
} else {
System.out.println("文本创建失败");
}
} catch (IOException e) {
e.printStackTrace();
}
}
// 创建第二个文本
File toFile2 = new File("D://copy - 副本.txt");
if (!toFile.exists()) {
try {
boolean newCopy = toFile2.createNewFile();
if (newCopy) {
System.out.println("文本创建成功");
} else {
System.out.println("文本创建失败");
}
} catch (IOException e) {
e.printStackTrace();
}
}
// 统计行数
try {
BufferedReader br = new BufferedReader(new FileReader(fromFile));
BufferedWriter bw = new BufferedWriter(new FileWriter(toFile));
int count = 0;
String str = br.readLine();
while (str != null) {
count++;
str = br.readLine();
}
System.out.println("这篇文章共有" + count + "行");
br.close();
// 写第一个文本
BufferedReader br2 = new BufferedReader(new FileReader(fromFile));
String content = "";
content = br2.readLine();
content += "\r\n";
System.out.println(content);
bw.write(content);
bw.flush();
bw.close();
// 写第二个文本
BufferedWriter bw2 = new BufferedWriter(new FileWriter(toFile2));
content += br2.readLine();
content += "\r\n";
bw2.write(content);
bw2.flush();
bw2.close();
// 写第三个及以后的文本
int a = 1;
int i = 2;
while (i++ < count) {
content += br2.readLine();
content += "\r\n";
BufferedWriter bw3 = new BufferedWriter(
new FileWriter(toFile + " " + "-" + " " + "副标" + " "
+ "(" + a + ")" + ".txt"));
//方便对照最终文件的数目
System.out.println("i is:" + i);
a++;
bw3.write(content);
bw3.flush();
bw3.close();
}
br2.close();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}