簡單文件讀寫
隨機訪問文件讀寫
NIO文件讀寫-FileChannel
使用MappedByteBuffer讀寫文件
簡單文件讀寫FileOutputStream由於流是單向的,簡單文件寫可使用FileOutputStream,而讀文件則使用FileInputStream。任何數據輸出到文件都是以字節為單位輸出,包括圖片、音頻、視頻。以圖片為例,如果沒有圖片格式解析器,那麼圖片文件其實存儲的就只是按某種格式存儲的字節數據罷了。FileOutputStream指文件字節輸出流,用於將字節數據輸出到文件,僅支持順序寫入、支持以追加方式寫入,但不支持在指定位置寫入。public class FileOutputStreamStu{
public void testWrite(byte[] data) throws IOException {
try(FileOutputStream fos = new FileOutputStream("/tmp/test.file",true)) {
fos.write(data);
fos.flush();
}
}
}
public class BufferedOutputStream extends FilterOutputStream {
public synchronized void write(byte b[], int off, int len) throws IOException {
if (len >= buf.length) {
flushBuffer();
out.write(b, off, len);
return;
}
if (len > buf.length - count) {
flushBuffer();
}
System.arraycopy(b, off, buf, count, len); // 只寫入緩存
count += len;
}
}
public class FileInputStreamStu{
public void testRead() throws IOException {
try (FileInputStream fis = new FileInputStream("/tmp/test/test.log")) {
byte[] buf = new byte[1024];
int realReadLength = fis.read(buf);
}
}
}
public class FileInputStreamStu{
public void testRead() throws IOException {
try (FileInputStream fis = new FileInputStream("/tmp/test/test.log")) {
int byteData = fis.read(); // 返回值取值範圍:[-1,255]
if (byteData == -1) {
return; // 讀取到文件尾了
}
byte data = (byte) byteData;
// data為讀取到的字節數據
}
}
}
public class FileInputStreamStu{
@Test
public void testRead() throws IOException {
try (FileInputStream fis = new FileInputStream("/tmp/test/test.log")) {
ByteBuffer buffer = ByteBuffer.allocate(1024);
int byteData;
while ((byteData = fis.read()) != -1) {
if (byteData == '\n') {
buffer.flip();
String line = new String(buffer.array(), buffer.position(), buffer.limit());
System.out.println(line);
buffer.clear();
continue;
}
buffer.put((byte) byteData);
}
}
}
}
public class RandomAccessFileStu{
public void testRandomWrite(long index,long offset){
try (RandomAccessFile randomAccessFile = new RandomAccessFile("/tmp/test.idx", "rw")) {
randomAccessFile.seek(index * indexLength());
randomAccessFile.write(toByte(index));
randomAccessFile.write(toByte(offset));
}
}
}
JNIEXPORT void JNICALL
Java_java_io_RandomAccessFile_seek0(JNIEnv *env,
jobject this, jlong pos) {
FD fd;
fd = GET_FD(this, raf_fd);
if (fd == -1) {
JNU_ThrowIOException(env, "Stream Closed");
return;
}
if (pos < jlong_zero) {
JNU_ThrowIOException(env, "Negative seek offset");
}
// #define IO_Lseek lseek
else if (IO_Lseek(fd, pos, SEEK_SET) == -1) {
JNU_ThrowIOExceptionWithLastError(env, "Seek failed");
}
}
public class FileChannelStu{
public void testGetFileCahnnel(){
try(FileOutputStream fos = new FileOutputStream("/tmp/test.log");
FileChannel fileChannel = fos.getChannel()){
// do....
}catch (IOException exception){
}
}
}
public class FileChannelStu{
public void testOpenFileCahnnel(){
FileChannel channel = FileChannel.open(
Paths.get(URI.create("file:" + rootPath + "/" + postion.fileName)),
StandardOpenOption.READ,StandardOpenOption.WRITE);
// do....
channel.close();
}
}
public class FileChannelStu{
public void testFileLock(){
FileChannel channel = this.channel;
FileLock fileLock = null;
try {
fileLock = channel.lock();// 獲取文件鎖
// 執行寫操作
channel.write(...);
channel.write(...);
} finally {
if (fileLock != null) {
fileLock.release(); // 釋放文件鎖
}
}
}
}
public class FileChannelStu{
public void testWrite(){
FileChannel channel = this.channel;
channel.write(...);
channel.write(...);
}
}
public class FileChannelStu{
public void closeChannel(){
this.channel.force(true);
this.channel.close();
}
}
JNIEXPORT jint JNICALL
Java_sun_nio_ch_FileDispatcherImpl_force0(JNIEnv *env, jobject this,
jobject fdo, jboolean md)
{
jint fd = fdval(env, fdo);
int result = 0;
if (md == JNI_FALSE) {
result = fdatasync(fd);
} else {
result = fsync(fd);
}
return handle(env, result, "Force failed");
}
public class FileChannelStu{
public void testSeekWrite(){
FileChannel channel = this.channel;
synchronized (channel) {
channel.position(100);
channel.write(ByteBuffer.wrap(toByte(index)));
channel.write(ByteBuffer.wrap(toByte(offset)));
}
}
}
public class FileChannelStu{
public void testSeekRead(){
FileChannel channel = this.channel;
synchronized (channel) {
channel.position(100);
ByteBuffer buffer = ByteBuffer.allocate(16);
int realReadLength = channel.read(buffer);
if(realReadLength==16){
long index = buffer.getLong();
long offset = buffer.getLong();
}
}
}
}
public class MappedByteBufferStu{
@Test
public void testMappedByteBuffer() throws IOException {
FileChannel fileChannel = FileChannel.open(Paths.get(URI.create("file:/tmp/test/test.log")),
StandardOpenOption.WRITE, StandardOpenOption.READ);
MappedByteBuffer mappedByteBuffer = fileChannel.map(FileChannel.MapMode.READ_WRITE, 0, 4096);
fileChannel.close();
mappedByteBuffer.position(1024);
mappedByteBuffer.putLong(10000L);
mappedByteBuffer.force();
}
}
public class MappedByteBufferStu{
@Test
public void testMappedByteBufferOnlyRead() throws IOException {
FileChannel fileChannel = FileChannel.open(Paths.get(URI.create("file:/tmp/test/test.log")),
StandardOpenOption.READ);
MappedByteBuffer mappedByteBuffer = fileChannel.map(FileChannel.MapMode.READ_ONLY, 0, 4096);
fileChannel.close();
mappedByteBuffer.position(1024);
long value = mappedByteBuffer.getLong();
System.out.println(value);
}
}