将byte[]流写入文件
/**
* 写byte[]流到文件中
* @param bytes
* @param path
* @return
*/
public static boolean writeByteToDisk(byte[] bytes,String path){
BufferedOutputStream bos = null;
FileOutputStream fos = null;
File file = new File(path);
if (!file.exists()) {
file.getParentFile().mkdirs();
}
try {
fos = new FileOutputStream(file);
bos = new BufferedOutputStream(fos);
bos.write(bytes);
bos.flush();
} catch (IOException e) {
e.printStackTrace();
return false;
} finally {
try {
bos.close();
} catch (IOException e) {
e.printStackTrace();
}
try {
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return true;
}
public static void main(String[] args) {
//测试
writeByteToDisk(new String("akdjhsakdhaskjdhasj").getBytes(),"/Users/xxxx/Desktop/test.json");
}
读取文件内容
/**
* 从文件中读取字符串内容
* @param file 读取的文件
* @return 返回文件字符串
*/
public static String readFile(File file) {
if(!file.exists())
return null;
StringBuffer result = new StringBuffer();
InputStreamReader isr = null;
FileInputStream fis = null;
BufferedReader br = null;
try {
fis = new FileInputStream(file);
isr = new InputStreamReader(fis);
br = new BufferedReader(isr);
String line;
while ((line = br.readLine()) != null) {
result.append(line);
}
} catch (IOException e) {
e.printStackTrace();
return null;
} finally {
try {
br.close();
} catch (IOException e) {
e.printStackTrace();
}
try {
fis.close();
} catch (IOException e) {
e.printStackTrace();
}
try {
isr.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return result.toString();
}
public static void main(String[] args) {
//测试
System.out.println(readFile(new File("/Users/xxxx/Desktop/test1.json")));
}
复制文件
/**
* 复制文件
* @param fromFile 源文件
* @param toFile 目标文件
* @return 返回结果
*/
public static boolean copyFile(File fromFile,File toFile){
FileOutputStream fos = null;
FileInputStream fio = null;
if (!toFile.exists()) {
toFile.getParentFile().mkdirs();
}
byte[] b = new byte[1024];
int len;
try {
fio = new FileInputStream(fromFile);
fos = new FileOutputStream(toFile);
while((len = fio.read(b)) !=-1){
fos.write(b,0,len);
}
} catch (IOException e) {
e.printStackTrace();
return false;
}finally {
try {
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
try {
fio.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return true;
}
public static void main(String[] args) {
//测试
copyFile(new File("/Users/xxxx/Desktop/test.json"),new File("/Users/xxxx/Desktop/test1.json"));
}
删除文件(如果是目录就是所有文件)
/**
* 递归删除目录下的所有文件及子目录下所有文件
*
* @param file 将要删除的文件目录
* @return true表示成功
*/
public static boolean deleteDir(File file) {
if (file.isDirectory()) {
File[] children = file.listFiles();
//递归删除目录中的子目录下
for (int i = 0; i < children.length; i++) {
boolean success = deleteDir(children[i]);
if (!success) {
return false;
}
}
}
// 目录此时为空,可以删除
return file.delete();
}
public static void main(String[] args) {
//测试
deleteDir(new File("/Users/xxxx/Desktop/debug"));
}