用Java封装一个自定义后缀的文件,存储文本
时间: 2024-02-12 10:09:06 浏览: 146
java学习笔记整理
好的,我可以为你提供一个Java类来封装一个自定义后缀的文件,并且可以用来存储文本。
以下是示例代码:
```java
import java.io.*;
public class CustomFile {
private String filename;
private String extension;
public CustomFile(String filename, String extension) {
this.filename = filename;
this.extension = extension;
}
public void writeTextToFile(String text) {
try {
String fullFilename = this.filename + "." + this.extension;
FileWriter writer = new FileWriter(fullFilename);
writer.write(text);
writer.close();
System.out.println("Text written to " + fullFilename + " successfully.");
} catch (IOException e) {
System.out.println("Error writing text to file.");
e.printStackTrace();
}
}
public String readTextFromFile() {
try {
String fullFilename = this.filename + "." + this.extension;
FileReader reader = new FileReader(fullFilename);
BufferedReader bufferedReader = new BufferedReader(reader);
StringBuilder stringBuilder = new StringBuilder();
String line;
while ((line = bufferedReader.readLine()) != null) {
stringBuilder.append(line);
stringBuilder.append(System.lineSeparator());
}
reader.close();
return stringBuilder.toString();
} catch (IOException e) {
System.out.println("Error reading text from file.");
e.printStackTrace();
return null;
}
}
}
```
这个类可以创建一个自定义后缀的文件,并且可以将文本写入到文件中。同时,它也可以从文件中读取文本。
你可以这样使用它:
```java
CustomFile customFile = new CustomFile("example", "txt");
customFile.writeTextToFile("Hello, world!");
String textFromFile = customFile.readTextFromFile();
System.out.println(textFromFile);
```
这将创建一个名为 "example.txt" 的文件,并将 "Hello, world!" 写入该文件。然后,它将从文件中读取文本,并将其打印到控制台上。
阅读全文