java编程将文件f1t乘t的内容读出来然后写入f2t乘t文件中
2个回答
展开全部
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
public class WriteToOther {
public static void main(String[] args) {
readFileByLines("old.txt");
}
/**
* 以行为单位读取文件,常用于读面向行的格式化文件
*/
public static void readFileByLines(String fileName) {
File file = new File(fileName);
BufferedReader reader = null;
try {
System.out.println("以行为单位读取文件内容,一次读一整行:");
reader = new BufferedReader(new FileReader(file));
String tempString = null;
while ((tempString = reader.readLine()) != null) {
// 显示行号
//
writeFileByLine(tempString);
}
reader.close();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (reader != null) {
try {
reader.close();
} catch (IOException e1) {
}
}
}
}
public static void writeFileByLine(String data) {
try {
File file = new File("new.txt");
// if file doesnt exists, then create it
if (!file.exists()) {
file.createNewFile();
}
// true = append file
FileWriter fileWritter = new FileWriter(file.getName(), true);
BufferedWriter bufferWritter = new BufferedWriter(fileWritter);
bufferWritter.append(data);
bufferWritter.append("\n");
bufferWritter.close();
System.out.println("Done");
} catch (IOException e) {
e.printStackTrace();
}
}
}
已赞过
已踩过<
评论
收起
你对这个回答的评价是?
展开全部
String encoding = "GBK";
try {
File file = new File("D:\\text.txt");
if (file.isFile() && file.exists()) { // 判断文件是否存在
InputStreamReader read = new InputStreamReader(
new FileInputStream(file), encoding);// 考虑到编码格式
BufferedReader bufferedReader = new BufferedReader(read);
String lineTxt = null;
StringBuffer sb = new StringBuffer();
while ((lineTxt = bufferedReader.readLine()) != null) {
sb.append(lineTxt).append("\r\n");
}
read.close();
File bFile = new File("D:\\text1.txt");
FileOutputStream out = new FileOutputStream(bFile);
PrintWriter pw = new PrintWriter(out);
pw.write(sb.toString());
pw.close();
out.close();
} else {
System.out.println("找不到指定的文件");
}
} catch (Exception e) {
System.out.println("读取文件内容出错");
e.printStackTrace();
}
本回答被网友采纳
已赞过
已踩过<
评论
收起
你对这个回答的评价是?
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询