java文件创建、RandomAccessFile的使用

(一)java.io.file表示文件(目录), file类只用于文件目录的访问,不能用于文件内容的访问。


File file=new File("D:\\学习笔记区\\文件测试1.txt");

测试文件是否存在:file.exists();

创建文件目录:file.mkdir();

创建txt文件:file2.createNewFile();

打印目录路径:file2.getAbsolutePath();
打印文件名,System.out.println(file.getName());
打印父目录的路径:System.out.println(file.getParent());

是否是个文件目录:file.isDirectory();

是否是个文件:file.isFile();

其他详细看api


代码如下:

package test0428;

import java.io.File;
import java.io.IOException;
import java.util.Scanner;

import org.omg.Messaging.SyncScopeHelper;

/*
 * java.io.file表示文件(目录)
 * file类只用于文件目录的访问,不能用于文件内容的访问
 * */
 //字符串判断
public class testFile {
	//了解构造函数,alt+/查看帮助
	public void method1(){
		 Scanner in=new Scanner(System.in);
		 
		 System.out.println("请选择");
		 String str=in.next();
		 switch(str){
		 case "abc":
			 System.out.println("abc");
			 break;
		 case "bcd":
			 System.out.println("bcd");
			 break;
		 default :
			 System.out.println("default");
			 break;
					 
		 }
		 
		 boolean flag1=true;
		 switch(flag1+""){
		 case "true":
			 System.out.println("boolean类型的:true");
			 break;
		 case "flase":
			 System.out.println("boolean类型的:flase");
			 break;
		 default :
			 System.out.println("default");
			 break;
					 
		 }
	}
	
	public static void main(String[] agrs){
	//测试文件是否存在的
	File file=new File("D:\\学习笔记区\\文件测试1.txt");
	System.out.println("判断文件是否存在,file.exists:"+file.exists());
	if(file.exists()){
		System.out.println("文件已经存在");
	}
	else{
		boolean flag=file.mkdir();
		System.out.println("文件不存在,文件创建:"+flag);//创建文件
	}
	System.out.println("是否是个文件目录:"+file.isDirectory());
	System.out.println("是否是个文件:"+file.isFile());
	//创建文件目录
	/*
	File file1=new File("D:\\学习笔记区\\文件测试1.txt");
	 boolean flag= file1.mkdir();
	 System.out.println("创建文件状态:"+flag);
	*/
	System.out.println("-------------创建txt文件-----------");
	File file2=new File("D:\\学习笔记区\\文件测试2.txt");
	//File file2=new File("D:\\学习笔记区","文件测试2.txt");
	if(!file2.exists()){
		try {
			//创建txt文件
			file2.createNewFile();
			System.out.println(file2);//打印file.toString
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	System.out.println(file2.getAbsolutePath());//打印目录路径
	System.out.println(file.getName());//打印文件名
	System.out.println(file.getParent());//打印父目录的路径
	}
	
}


运行结果:

判断文件是否存在,file.exists:true
文件已经存在
是否是个文件目录:true
是否是个文件:false
-------------创建txt文件-----------
D:\学习笔记区\文件测试2.txt
D:\学习笔记区\文件测试2.txt
文件测试1.txt
D:\学习笔记区


(二)RandomAccessFile的使用

(1)文件模型  byte  byte byte
 RandomAccessFile,java提供既可以提供对文件内容的访问,既可以读文件,也可以写文件,
 支持随机访问文件,可以访问文件的任意位置。
(2)打开文件两种方式:rw读写,r是只读 RandomAccessFile RandomAccessFile=new RandomAccessFile(file,"rw");
文件指针,打开指针时候,pointer == 0;
(3)写方法 raf.write(int)  --只写一个字节()后8位.同时指针指向下一个位置准备再次写入。
(4)读方法int b=raf.read()  --读一个字节
(5)文件读写完以后一定要关闭(oracle官方说明)会有异常


代码如下:

package test0428;

import static org.junit.Assert.*;

import java.io.File;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.util.Arrays;
import java.util.Scanner;

import org.junit.Test;

public class Test0430 {

  /*IO流
   * 输入流  输出流
   * 字节流 字符流
   * fileinputstream
   * (1)字节流  inputstream  outputstream
   * inputstream抽象了应用程序读取的方式
   * outputstream抽象了应用程序写出数据的方式
   * 
   * (2)EOF=end,-1结尾
   * (3)输入流
   * (4)输出流基本方法
   * (5)FileInputStream 具体实现了文件中读取数据
   * */
	@Test
	public void fileinputstream()throws IOException{
		
	}
	
	/*(1)文件模型  byte  byte byte
	 * RandomAccessFile,java提供既可以提供对文件内容的访问,既可以读文件,也可以写文件,
	 * 支持随机访问文件,可以访问文件的任意位置。
	 * (2)打开文件两种方式:rw读写,r是只读
	 * RandomAccessFile RandomAccessFile=new RandomAccessFile(file,"rw");
	 * 文件指针,打开指针时候,pointer == 0;
	 * (3)写方法
	 * raf.write(int)  --只写一个字节()后8位.同时指针指向下一个位置准备再次写入。
	 * (4)读方法
	 * int b=raf.read()  --读一个字节
	 * (5)文件读写完以后一定要关闭(oracle官方说明)会有异常
	 * */
	
	@Test
	public void IORandomAccessFileTest()throws IOException{
		File demo=new File("demo");
		if(!demo.exists())demo.mkdirs();
		File files=new File(demo,"raf.dat");
		if(!files.exists())files.createNewFile();
		RandomAccessFile raf=new RandomAccessFile(files,"rw");
		//指针的位置
		System.out.println(raf.getFilePointer());
		raf.write('A');
		System.out.println(raf.getFilePointer());
		raf.write('B');
		System.out.println(raf.getFilePointer());
		String s="中国";
		byte[] mystr=s.getBytes("gbk");
		raf.write(mystr);
		System.out.println(raf.getFilePointer());
		
		//读文件必须把指针移到头部
		raf.seek(0);
		//一次性读取,吧文件内容都读到字节数组
		byte[] byt=new byte[(int)raf.length()];
		raf.read(byt);
		System.out.println(Arrays.toString(byt));
		String ss=new String(byt);
		System.out.println(ss);
		raf.close();//关闭
	}
	
	public void listDeteractery(File dir)throws IOException{
		if(!dir.exists()){
			throw new IllegalArgumentException("目录:"+dir+"不存在!");
		}
		if(!dir.isDirectory()){
			throw new IllegalArgumentException("目录:"+dir+"不是目录!");
		}
	//	String[] finenames= dir.list();//查看目录下有什么文件
	//	for(String name:finenames){
	//		System.out.println("name:"+name);
	//	}
	//	System.out.println("==================================");
		//如果遍历子目录下,要递归循环
		File[] files=dir.listFiles();
		if(files!=null  && files.length>0){
			for(File fileName:files){
			//	System.out.println("fileName:"+fileName);
				if(fileName.isDirectory()){
					//递归
					listDeteractery(fileName);
				}
				else{
					System.out.println(fileName);
				}
			}
		}
		
	}
	
	@Test
	public void test() throws IOException {
	//	listDeteractery(new File("D:\\学习笔记区\\文件测试1.txt"));
	//	IORandomAccessFileTest();
		Scanner in=new Scanner(System.in);
		String str=in.next();//输入字符串
		
	}

}
运行结果:


(1)IORandomAccessFileTest的test测试运行结果:

0
1
2
6
[65, 66, -42, -48, -71, -6]
AB中国

(2)


  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
使用MappedByteBuffer可以将文件直接映射到内存中,通过内存操作来读写文件,从而提高性能。下面是使用MappedByteBuffer的示例代码: ```java try { // 创建 RandomAccessFile 对象 RandomAccessFile file = new RandomAccessFile("path/to/file.txt", "rw"); // 获取文件通道 FileChannel channel = file.getChannel(); // 将文件映射到内存中 MappedByteBuffer buffer = channel.map(FileChannel.MapMode.READ_WRITE, 0, channel.size()); // 读取数据 byte[] data = new byte[buffer.limit()]; buffer.get(data); // 写入数据 String content = "Hello, World!"; buffer.put(content.getBytes()); // 刷新缓冲区内容到磁盘 buffer.force(); // 关闭资源 channel.close(); file.close(); } catch (IOException e) { e.printStackTrace(); } ``` 在上述代码中,首先通过RandomAccessFile对象获取文件通道,然后通过`map()`方法将文件映射到内存中的MappedByteBuffer对象。通过该对象可以直接对文件进行读写操作。 读取数据时,可以通过`get()`方法从MappedByteBuffer中获取字节数据。写入数据时,可以通过`put()`方法将字节数据写入MappedByteBuffer。 需要注意的是,在进行写入操作后,最好调用`force()`方法刷新缓冲区内容到磁盘,以确保数据被持久化保存。 最后,记得关闭资源,释放系统资源。 使用MappedByteBuffer可以减少磁盘I/O次数,提高读写性能,但需要注意内存映射文件的大小限制,过大的文件可能会导致内存溢出。此外,MappedByteBuffer适用于较大的文件读写,对于小文件可能带来较小的性能提升。因此,应根据具体情况评估是否使用MappedByteBuffer来优化RandomAccessFile的性能。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值