优化以下代码运行速度public void test(String rootPath){ String path= rootPath+"/emmctest.txt"; File file = new File(path); // 向文件写入内容(输出流) int btcount = 1024 * calculateAvailableMem[i]; byte bt[] = new byte[btcount]; try { FileOutputStream in = new FileOutputStream(file); in.write(bt); in.flush(); FileDescriptor fd = in.getFD(); fd.sync(); in.close(); } catch (IOException e) { e.printStackTrace(); Log.d(TAG, "EMMCTest test failed"); } deleteTestFile(path); }
时间: 2024-01-22 19:02:38 浏览: 78
首先,需要了解calculateAvailableMem[i]的值,它是如何获得的。如果它是一个已知的常量,可以将计算结果直接放在代码中,而不是每次计算都要去获取一遍。
其次,可以使用BufferedOutputStream代替FileOutputStream,以减少写入文件的次数,如下所示:
```
public void test(String rootPath) {
String path = rootPath + "/emmctest.txt";
File file = new File(path);
// 向文件写入内容(输出流)
int btcount = 1024 * calculateAvailableMem[i];
byte bt[] = new byte[btcount];
try {
BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(file));
out.write(bt);
out.flush();
out.close();
} catch (IOException e) {
e.printStackTrace();
Log.d(TAG, "EMMCTest test failed");
}
deleteTestFile(path);
}
```
最后,可以使用try-with-resources语句来自动关闭输出流,如下所示:
```
public void test(String rootPath) {
String path = rootPath + "/emmctest.txt";
File file = new File(path);
// 向文件写入内容(输出流)
int btcount = 1024 * calculateAvailableMem[i];
byte bt[] = new byte[btcount];
try (BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(file))) {
out.write(bt);
out.flush();
} catch (IOException e) {
e.printStackTrace();
Log.d(TAG, "EMMCTest test failed");
}
deleteTestFile(path);
}
```
这样可以避免手动关闭输出流的疏忽。
阅读全文