62,623
社区成员
发帖
与我相关
我的任务
分享
import java.io.*;
import javax.swing.*;
public class Main {
/**
* 一些文件操作
* @param inFilePath 读入的文件名
* @param outFilePath 写入的文件名
* @param append 是否附加在尾部
*/
public void doSomething(String inFilePath,String outFilePath,boolean append){
File fileIn = new File(inFilePath);
File fileOut = new File(outFilePath);
try {
FileInputStream fis = new FileInputStream(fileIn);
FileOutputStream fos = new FileOutputStream(fileOut,append);
byte[] b = new byte[1]; // 1个byte数组
while((fis.read(b)) != -1){ // 一个个的读字节
fos.write(b); // 一个个的写到输出流中
}
fos.close();
fis.close();
new JOptionPane().showMessageDialog(null, "操作完成!");
} catch (FileNotFoundException fnfe) {
fnfe.printStackTrace();
} catch(IOException ioe){
ioe.printStackTrace();
}
}
/**
* 选择打开文件
* @param title
* @return
*/
public String chooseFileOpen(String title){
JFileChooser chooser = new JFileChooser();
chooser.setDialogTitle(title);
int i = chooser.showOpenDialog(null);
if(i == JFileChooser.APPROVE_OPTION){
return chooser.getSelectedFile().getAbsolutePath();
}
else{
return "";
}
}
/**
* 设置保存文件
* @param title
* @return
*/
public String chooseFileSave(String title){
JFileChooser chooser = new JFileChooser();
chooser.setDialogTitle(title);
int i = chooser.showSaveDialog(null);
if(i == JFileChooser.APPROVE_OPTION){
return chooser.getSelectedFile().getAbsolutePath();
}
else{
return "";
}
}
public static void main(String[] args) {
// new Main().doSomething("D:/1.txt", "D:/2.txt", false);
Main test = new Main();
test.doSomething(test.chooseFileOpen("选择文件"),test.chooseFileSave("保存文件"), true);
}
}