public class FileWrite {
public File file;
public FileOutputStream stream = null;
//每次写入都会覆盖之前的内容
public void writeData(String name,String data){
try{
String path = "E:/data/" + name +".txt";
file = new File(path);
stream = new FileOutputStream(file);
if(!file.exists()){
file.createNewFile();
}
byte[] contentInbytes = data.getBytes();
stream.write(contentInbytes);
stream.flush();
stream.close();
}catch (FileNotFoundException e){
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
//在末尾追加内容,不会覆盖之前的内容
public void write(String name,String data){
try{ String path = "E:/data/" + name +".txt";
file = new File(path);
FileWriter fw = new FileWriter(file,true);
PrintWriter pw = new PrintWriter(fw);
pw.print(data);
pw.flush();
pw.close();
fw.close();
}catch (IOException e){
e.printStackTrace();
}
}
}