Recently doing a project, you need to create multi-threaded file.
Used RandomAccessFile class
RandomAccessFile is Java I / O stream system, the most feature-rich file access class content, can either read the contents of the file, you can also export data to a file. Ordinary input / output streams is different, RandomAccessFile supporting jump anywhere file read and write data, RandomAccessFile object contains a record pointer, which identifies the current position of the read and write at, when creating a new RandomAccessFile target program, the record pointer for the file object file header (i.e. 0), when the n bytes read, file record pointer will move rearwardly n bytes. In addition, RandomAccessFile the record pointer can move freely
RandomAccessFile contains two methods to manipulate the file record pointer:
- long getFilePointer (): returns the current position of the file record pointer
- void seek (long pos): record a file pointer to locate the position pos
RandomAccessFile class object creation, in addition to the specified file itself, also need to specify a mode parameter that specifies access mode RandomAccessFile This parameter has the following four values:
- r: Open the specified file in read-only mode. If you try to execute the file specified RandomAccessFile writing method will throw IOException
- rw: to read, write, open the specified file. If the file does not exist, try to create a file
- rws: to read, write, open the specified file. Rw relative mode is also required for each update content file or metadata are written synchronously to the underlying storage device, the default condition (the mode rw), the buffer is used, only the full cache or use RandomAccessFile.close () Closes the stream when children really written documents
- rwd: rws with similar, but only the contents of the file synchronization updates to disk, without modifying the metadata file
I think it is more important than the need to know, not much to say, on the code
import android.os.Bundle;
import android.os.Environment;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import java.io.File;
public class CreateFile extends AppCompatActivity implements View.OnClickListener {
private static final String TAG = CreateFile.class.getSimpleName();
@Override
protected void onCreate(Bundle saveInstanceState) {
super.onCreate(saveInstanceState);
setContentView(R.layout.create_file);
Button startButton = findViewById(R.id.create_file_button);
startButton.setOnClickListener(this);
}
@Override
public void onClick(View v) {
int threadNum = 8;
int fileSize = 1024 * 1024;
createFile(threadNum, fileSize);
}
private void createFile(int threadID, int fileSize) {
String folderPath = Environment.getExternalStorageDirectory().getPath() + File.separator + "demoTest" + File.separator;
Log.d(TAG, "create file path : " + folderPath);
File file = new File(folderPath);
if (!file.exists() && !file.isDirectory()) {
file.mkdirs();
}
//创建大小是1G的文件
MoreThreadCreateFile moreThreadCreateFile = new MoreThreadCreateFile(folderPath + "aa.txt", fileSize, threadID);
moreThreadCreateFile.start();
}
class MoreThreadCreateFile extends Thread {
private String mFilePath;
private int mFileSize;
private int mThreadNum;
MoreThreadCreateFile(String filePath, int fileSize, int threadNum) {
mFilePath = filePath;
mFileSize = fileSize;
mThreadNum = threadNum;
}
@Override
public void run() {
//todo
FileCreateThread[] threads = new FileCreateThread[mThreadNum];
try {
int blockSize = (mFileSize % mThreadNum) == 0 ? mFileSize / mThreadNum : mFileSize / mThreadNum + 1;
File file = new File(mFilePath);
for (int i = 0; i < threads.length; i++) {
threads[i] = new FileCreateThread(file, blockSize, i + 1);
threads[i].setName("Thread:" + i);
threads[i].start();
}
Log.d(TAG, "file create is complete!!");
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
import android.util.Log;
import java.io.File;
import java.io.IOException;
import java.io.RandomAccessFile;
class FileCreateThread extends Thread {
private static final String TAG = FileCreateThread.class.getSimpleName();
//线程创建的长度
private int mFileLenth;
//文件路径
private File mFile;
//线程ID
private int mThreadId;
//线程下载的长度
private int mBlockSize;
public FileCreateThread(File file, int blockSize, int threadId) {
mFile = file;
mBlockSize = blockSize;
mThreadId = threadId;
}
@Override
public void run() {
RandomAccessFile raf = null;
try {
int startPos = mBlockSize * (mThreadId - 1);//开始位置
int endPos = mBlockSize * mThreadId - 1; //结束位置
//文件的长度
mFileLenth = endPos - startPos;
Log.d(TAG, "mFileLenth =" + mFileLenth);
raf = new RandomAccessFile(mFile, "rwd");
raf.seek(startPos);
int len = 0;
while (len < mFileLenth / 128 + 1) {
raf.write(buffer1K());
len++;
}
isCompleted = true;
} catch (Exception e) {
e.printStackTrace();
} finally {
if (raf != null) {
try {
raf.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
private byte[] buffer1K() {
byte[] by = new byte[128];
for (int item = 0; item < by.length; item++) {
by[item++] = 0x5;
by[item] = 0xA;
}
return by;
}
}
Reference blog: