这个类是我用Java写一个小工具时写的,在文章里介绍得很详细了,如果耐心看完代码前近乎面向初学者的介绍内容,用起来是很方便也很简单的,当然代码中还有一些需要改进的地方,后面有时间会完善,如果有读者发现,大家不妨在评论中提出来,互相学习。
- 相关参数和方法注释
textRead:[类型:String] [作用:从指定目录的文件中读取的内容]
textSet:[类型:String] [作用:接收从外部传入的字符串,将会写入指定目录的文件中]
routeSet:[类型:String] [作用:接收从外部传入的需要写入或读取的指定文件的目录,如"D:\record.txt"]
appendSet:[类型:boolean] [作用:如接收到true,写textSet进入指定目录的文件中时会覆盖写,如为false,则在已有内容后追加写入]
newLineSet:[类型:int] [作用:默认为0,即写textSet进入指定目录的文件中时每一次写操作都会直接追加在上次内容之后,如接收到1,则在追加写的条件下,每一次写操作都会换行写入]
- 相关方法的注释:
writeInfo():写textSet进入指定routeSet的文件中,此时还需指定appendSet,newLineSet默认为0,可缺省;
readInfo():在指定routeSet的文件存在的情况下,从指定routeSet的文件中读取textRead并通过getText把读取内容return;
existAndDelete():如果指定routeSet的文件存在则删除该文件;
- 方法如何调用?
readInfo()
FileOperation rfo = new FileOperation();
rfo.setRouteGet("record.txt"); //此处使用相对路径
rfo.readInfo();
System.out.println(rfo.getText());
writeInfo()
FileOperation fop = new FileOperation();
fop.setRouteGet("record.txt");
fop.setTextGet("要写入的内容");
fop.setAppend(false);
fop.writeInfo();
existAndDelete()
FileOperation fop = new FileOperation();
fop.existAndDelete();
- 工具类代码:
package pers.slvayf.aio.boost;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;
/**
*
* @author slvayf
*
*/
public class FileOperation {
private String textRead = "";
private String textSet;
private String routeSet;
private boolean appendSet;
private int newLineSet = 0;
public void setNewLine(int newLine) {
this.newLineSet = newLine;
}
public void setAppend(boolean append) {
this.appendSet = append;
}
public String getText() {
return textRead;
}
public void setTextGet(String text) {
this.textSet = text;
}
public void setRouteGet(String route) {
this.routeSet = route;
}
public void writeInfo() {
OutputStreamWriter writeUseracc = null;
try {
writeUseracc = new OutputStreamWriter(new FileOutputStream(this.routeSet, this.appendSet), "GBK");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (FileNotFoundException e) {
e.printStackTrace();
}
try {
writeUseracc.write(this.textSet);
if (newLineSet == 1) {
writeUseracc.write("\r\n");
}
} catch (IOException e) {
e.printStackTrace();
}
try {
writeUseracc.close();
} catch (IOException e) {
e.printStackTrace();
}
}
public void readInfo() {
File fileUse = new File(this.routeSet);
String textReadChar;
if (fileUse.exists()) {
try {
FileInputStream getText = new FileInputStream(this.routeSet);
try {
int n = 0;
while ((n = getText.read()) != -1) {
textReadChar = String.valueOf((char) n);
this.textRead = this.textRead + textReadChar;
}
getText.close();
} catch (IOException e) {
e.printStackTrace();
}
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
}
public void existAndDelete() {
File fileUse = new File(this.routeSet);
if (fileUse.exists()) {
fileUse.delete();
}
}
}