I need to create an empty binary file with given size in java. What is the fastest way to do this? I also need to update UI simultaneously. I use following code to do this. But it’s not very fast. Can everyone help me? Tnx
public static void create(String pathAndName, int fileSize) {
FileOutputStream fileOutputStream = null;
try {
fileOutputStream = new FileOutputStream(pathAndName);
int length = 10 * 1024;
byte[] buffer = new byte[length];
int len = buffer.length;
int createdSize = 0;
int percent = 0;
int lastPercent = 0;
while (createdSize < fileSize) {
createdSize += length;
if (createdSize > fileSize) {
len = fileSize - (createdSize - length);
}
lastPercent = percent;
percent = (int) (((double) createdsize / fileSize) * 100);
if(lastPercent != percent){
updateUI(percent);
}
fileOutputStream.write(buffer, 0, len);
}
} catch (Exception e) {
e.printStackTrace();
}
if (fileOutputStream != null) {
try {
fileOutputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}