62,628
社区成员
发帖
与我相关
我的任务
分享
public class Test {
/*
* 原始文本 新文本
* 1 1
* 2 2
* 3 3
* 4 XXXXXX
* 4
*/
public static void main(String[] args) {
String txtPath = "E:/1.txt";// 文件路径
String addContent = "XXXXXX";// 加入的内容
List<String> contentByLine = readTxtLine(txtPath);
contentByLine.add(contentByLine.size() - 1, addContent);//把添加的内容加到倒数第二行
writeContent(txtPath, contentByLine);
}
private static List<String> readTxtLine(String txtPath) {
String lineContent = null;
InputStream in = null;
InputStreamReader read = null;
BufferedReader reader = null;
List<String> strs = new ArrayList<String>();
try {
File txtFile = new File(txtPath);
in = new FileInputStream(txtFile);
read = new InputStreamReader(in, "GBK");
reader = new BufferedReader(read);
while ((lineContent = reader.readLine()) != null)// 将文本内容逐行插入List中
strs.add(lineContent);
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
reader.close();
read.close();
in.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return strs;
}
private static void writeContent(String filePath, List<String> newContent) {
FileOutputStream out = null;
try {
out = new FileOutputStream(filePath);
out.write("".getBytes());
for (String entity : newContent) {
entity += "\r\n";// 添加换行符
out.write(entity.getBytes());
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
out.flush();
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
import java.io.*;
public class readAndWrite
{
private BufferedReader bufferReadin=new BufferedReader(new FileReader("D:/TestR.txt"));
private PrintWriter bufferWriter=new PrintWriter( new BufferedWriter(new FileWriter("D:/TestWrite.txt")));
String[] sArray=new String[20];
String s=null;
int iline=0;//行数
public readAndWrite()throws IOException
{
while((s=bufferReadin.readLine())!=null)//先读一遍统计行数
{
System.out.println(s);
sArray[iline]=s;
iline++;
}
int ilastSecondLine=iline-1;
iline=0;
while((s=sArray[iline])!=null)
{
if(ilastSecondLine==iline)//读到倒数第二行插入
{
bufferWriter.println("倒数第二行插入");
}
System.out.println(s);
bufferWriter.println(s);
iline++;
}
bufferReadin.close();
bufferWriter.close();
}
public static void main(String[] args) throws IOException
{
readAndWrite Test=new readAndWrite();
}
}