任意找一个.java 文件,把该文件的每一行读取到一个 String 数组中,然后在每一行前面加上一个行号,重新写入到该文件。
(要求使用 BufferedReader 和 BufferedWriter)
package bufferedreader;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
public class test {
public static void main(String[] args) {
File file=new File("C:/Users/xzy/Desktop/JoinExample.java");
try {
FileInputStream fileInputStream=new FileInputStream(file);
InputStreamReader inputStreamReader=new InputStreamReader(fileInputStream);
BufferedReader bufferedReader=new BufferedReader(inputStreamReader);
int n=0;
while ((bufferedReader.readLine())!=null) {
n++;
}
FileInputStream fileInputStream1=new FileInputStream("C:/Users/xzy/Desktop/JoinExample.java");
InputStreamReader fileReader1=new InputStreamReader(fileInputStream1);
BufferedReader bufferedReader1=new BufferedReader(fileReader1);
String[] line=new String[n];
while ((bufferedReader1.readLine())!=null) {
for (int i = 0; i < line.length; i++) {
line[i]=(i+"--"+bufferedReader1.readLine());
}
}
FileWriter fileWriter=new FileWriter("C:/Users/xzy/Desktop/JoinExample.java");
BufferedWriter bufferedWriter=new BufferedWriter(fileWriter);
for (int j = 0; j < line.length; j++) {
bufferedWriter.newLine();
bufferedWriter.write(line[j]);
}
inputStreamReader.close();
bufferedReader.close();
bufferedReader1.close();
bufferedWriter.close();
} catch (FileNotFoundException e) {
// TODO 自动生成的 catch 块
e.printStackTrace();
} catch (IOException e) {
// TODO 自动生成的 catch 块
e.printStackTrace();
}
}
}
涉及知识点:文本流 ————如不了解可观看下方视频。
视频来源于学吧内部,不可转载。如果视频侵犯了您的权利,联系我们,我们将删除。
项目文件下载链接:点击下载
转载请注明:转自TeenShare 梯云分享