`
cloudeagle_bupt
  • 浏览: 541131 次
文章分类
社区版块
存档分类
最新评论

RandomAccessFile发生java.io.FileNotFoundException

 
阅读更多

本来以为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目录后,方可自行创建文件。
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics