我有byte[],我想将这个byteArray保存到一个文件中,为此我编写了以下代码:
File root = new File(App.getAppCacheDir(baseActivity) + "/user/");
if (!root.exists()) root.mkdirs();
File file = new File(root, "user.jpg");
writeBytesToFile(userImage,file);
首先我创建了 patha,然后我为我的文件设置了一个名称,最后我将路径和我的字节数组传递给我的方法。
这是我的方法:
private void writeBytesToFile(byte[] bFile, File fileDest) {
try {
FileOutputStream fOut = new FileOutputStream(fileDest);
fOut.write(bFile);
fOut.close();
}catch (IOException e) {
e.printStackTrace();
}
}
但是没有为我的地址创建文件?我的错误在哪里?
试试这个
File root = new File(App.getAppCacheDir(baseActivity) + "/user/");
if (!root.exists()) root.mkdirs();
File file = new File(root, "user.jpg");
if (!file.exists()) file.createNewFile();
writeBytesToFile(userImage,file);
String s = "Java Code Geeks - Java Examples";
File file = new File("outputfile.txt");
FileOutputStream fos = null;
try {
fos = new FileOutputStream(file);
// Writes bytes from the specified byte array to this file output stream
fos.write(s.getBytes());
}
catch (FileNotFoundException e) {
System.out.println("File not found" + e);
}
catch (IOException ioe) {
System.out.println("Exception while writing file " + ioe);
}
finally {
// close the streams using close method
try {
if (fos != null) {
fos.close();
}
}
catch (IOException ioe) {
System.out.println("Error while closing stream: " + ioe);
}
}