---
title: "RandomAccessFile发生java.io.FileNotFoundException"
author: "cloudeagle_bupt"
date: "2016-08-21T16:55:00Z"
tags: []
slug: "randomaccessfile-java-io-filenotfoundexception"
draft: false
lastmod: "2016-11-23T20:47:15Z"
id: 2340187
url: "https://cloudeagle-bupt.iteye.com/blog/2340187"
---

本来以为RandomAccessFile在没有文件时, rw模式会自动创建文件，结果写如下代码时，报java.io.FileNotFoundException 异常.

```
package shareMemory;

import java.io.IOException;
import java.io.RandomAccessFile;
import java.nio.MappedByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.channels.FileChannel.MapMode;

public class MappedByteBufferTest {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		String str = "XXXXXXXXERXXXR" ;
		MappedByteBuffer mbb;
	    try {
	    	String outputFile = "F:\\test\\shareMemory\\test\\sharememory.txt";
	    	RandomAccessFile raf = new RandomAccessFile(outputFile, "rw");
		    FileChannel fc = raf.getChannel();
			mbb = fc.map(MapMode.READ_WRITE, 0, 1024);
			mbb.put(str.getBytes());
			raf.close() ;
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

}
```

发现原因是RandomAccessFile 不能跨目录创建文件。  
比如原目录是test\\\\shareMemory\\  
则只能在该目录下直接创建，如果想让其直接创建test\\\\shareMemory\\test\\a.file  
就会报文件找不到的异常。因此必须手动创建test\\\\shareMemory\\test目录后，方可自行创建文件。