创建了一个类,在构造方法中初始化用户输入的要覆盖的文件;在resetChar()方
法中实现覆盖。
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
public class File15_9 {
String sourceName = ""; //要覆盖的文件名
public File15_9() { //在构造函数中实现获取用户输入的文件路径
sourceName = getString();
}
public void resetChar() throws IOException {
File sourceFile = new File(sourceName); //创建File对象,实现对sourcenName的引用
FileInputStream fis = new FileInputStream(sourceFile); //打开一个到实际文件的链接
int count = 0; //统计文件中字符的个数
int ch = 0; //用于判断是否读到文件尾
do {
ch = fis.read(); //读取
if(ch != -1) {
count++;
}
}while(ch != -1);
fis.close();
FileOutputStream fos = new FileOutputStream(sourceFile); //创建一个向指定File对象表示的文件中写入数据的文件输出流
int temp = '0';
while((count--) != 0) {
fos.write(temp);
}
fos.close();
}
private String getString() { //获取用户输入的要覆盖的文件路径
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String str = "";
try {
System.out.println("请输入要进行覆盖的文件的完整路径");
str = br.readLine();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return str;
}
}法中实现覆盖。
本文介绍了一种使用Java编程语言实现文件覆盖功能的方法。通过构造函数获取用户输入的文件路径,利用File类操作文件,并在resetChar()方法中实现了对指定文件的覆盖。包括读取文件内容、统计字符数量、清空文件内容并重新写入特定字符的过程。
988

被折叠的 条评论
为什么被折叠?



