自己整理了个文件读写选择器的类,方便以后需要的时候拿来用,不用辛辛苦苦从头再写。可根据具体需要截取其中的某个方法到项目中使用。
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.filechooser.FileFilter;
/**
*
* @author ahomeeye
*/
public class ReadAndWrite extends JFrame {
private String path;
//打开文件,获取绝对路径
public void openFile() {
JFileChooser jfc = new JFileChooser();
jfc.setFileFilter(new FileFilter() {
public boolean accept(File f1) {
if (f1.isDirectory() || f1.getName().trim().endsWith(".properties")) { //默认问题类型为.properties
return true;
}
return false;
}
public String getDescription() {
return "properties文件";
}
});
int optionNum = jfc.showOpenDialog(getContentPane());
if (optionNum == JFileChooser.APPROVE_OPTION) {// 选择确认(yes、ok)
// 后返回该值。
File f1 = jfc.getSelectedFile();
path = f1.getAbsolutePath();
}
}
//写入内容
public void writer(String filePath) {
BufferedWriter bw = null;
try {
bw = new BufferedWriter(new OutputStreamWriter(
new FileOutputStream(filePath, false), "utf8"));
bw.write("这是新添的内容。");
bw.flush();
} catch (FileNotFoundException e1) {
} catch (IOException e1) {
} finally {
if (bw != null) {
try {
bw.close();
} catch (Exception e2) {
}
}
}
}
//读取内容
public void reader(String filePath) {
try {
try {
BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(filePath), "utf8"));
StringBuilder sb = new StringBuilder();
String str = "";
try {
while ((str = br.readLine()) != null) {
sb.append(str);
sb.append("\n");
}
} catch (IOException ex) {
}
System.out.println("sb=" + sb.toString());
} catch (FileNotFoundException ex) {
}
} catch (UnsupportedEncodingException ex) {
}
}
public static void main(String[] args) {
ReadAndWrite rw = new ReadAndWrite();
rw.openFile();
System.out.println("path=" + rw.path);
}
}