讀取文件
public String readFile(String filePath){
String str = "";//用來保存讀取的內容
StringBuffer buffer = new StringBuffer(str);//使用StringBuffer來拼接字符串
FileInputStream fis = null;
BufferedInputStream bis = null;
try {
fis = new FileInputStream(new File(filePath));
bis = new BufferedInputStream(fis);
int len = 0;
byte[] temp = new byte[1024];
while((len = bis.read(temp)) != -1){
buffer.append(new String(temp, 0, len));
}
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally {
try {
fis.close();
bis.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return buffer.toString();
}
寫入文件
public void writeFile(String str, String filePath){
BufferedOutputStream bos = null;
FileOutputStream fos = null;
File file = null;
try{
file = new File(filePath);
if(!file.exists() && file.isDirectory()){//如果文件不存在並且是一個文件夾
file.mkdirs();
}
fos = new FileOutputStream(file);
bos = new BufferedOutputStream(fos);
bos.write(str.getBytes());
} catch(Exception e) {
e.printStackTrace();
} finally {
try {
fos.close();
bos.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}