Java NIO 读取文件、写入文件、读取写入混合 还有 按行读取文件

前言

Java NIO(new/inputstream outputstream)使用通道、缓冲来操作流,所以要深刻理解这些概念,尤其是,缓冲中的数据结构(当前位置(position)、限制(limit)、容量(capacity)),这些知识点要通过写程序慢慢体会。

 

NIO vs  传统IO

NIO是面向缓冲、通道的;传统IO面向流

通道是双向的既可以写、也可以读;传统IO只能是单向的

NIO可以设置为异步;传统IO只能是阻塞,同步的

 

 

缓冲区结构图

NIO是面向缓冲区的,缓冲区可以理解为一块内存,有大小。缓冲区有位置、界限、容量几个概念。

 

capacity:容量,缓冲区的大小

limit:限制,表示最大的可读写的数量

position:当前位置,每当读写,当前位置都会加一

 

flip和clear方法,内部就操作这三个变量。

缓冲区常用方法

clear:将当前位置设置为0,限制设置为容量,目的是尽最大可能让字节,由通道读取到缓冲中

flip:当前位置置为限制,然后将当前位置置为0,目的是将有数据部分的字节,由缓冲写入到通道中。通常用在读与写之间。

package com.nio;

import java.io.*;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.charset.Charset;

public class TestJavaNio {

    public static String pathname = "d://read.txt";
    public static String filename = "d://write.txt";

    @SuppressWarnings("resource")
    public static void main(String[] args) {
        readNIO();
        writeNIO();
        //testReadAndWriteNIO();
    }

    public static void readNIO() {
        FileInputStream fin = null;
        try {
            fin = new FileInputStream(new File(pathname));
            FileChannel channel = fin.getChannel();

            int capacity = 1000;// 字节
            ByteBuffer bf = ByteBuffer.allocate(capacity);
            System.out.println("限制是:" + bf.limit() + ",容量是:" + bf.capacity() + " ,位置是:" + bf.position());
            int length = -1;

            while ((length = channel.read(bf)) != -1) {

                /*
                 * 注意,读取后,将位置置为0,将limit置为容量, 以备下次读入到字节缓冲中,从0开始存储
                 */
                bf.clear();
                byte[] bytes = bf.array();
                System.out.println("start..............");

                String str = new String(bytes, 0, length);
                System.out.println(str);
                //System.out.write(bytes, 0, length);

                System.out.println("end................");

                System.out.println("限制是:" + bf.limit() + "容量是:" + bf.capacity() + "位置是:" + bf.position());

            }

            channel.close();

        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (fin != null) {
                try {
                    fin.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    public static void writeNIO() {
        FileOutputStream fos = null;
        try {

            fos = new FileOutputStream(new File(filename));
            FileChannel channel = fos.getChannel();
            ByteBuffer src = Charset.forName("utf8").encode("你好你好你好你好你好");
            // 字节缓冲的容量和limit会随着数据长度变化,不是固定不变的
            System.out.println("初始化容量和limit:" + src.capacity() + ","
                    + src.limit());
            int length = 0;

            while ((length = channel.write(src)) != 0) {
                /*
                 * 注意,这里不需要clear,将缓冲中的数据写入到通道中后 第二次接着上一次的顺序往下读
                 */
                System.out.println("写入长度:" + length);
            }

        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (fos != null) {
                try {
                    fos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    public static void testReadAndWriteNIO() {
        FileInputStream fin = null;
        FileOutputStream fos = null;
        try {
            fin = new FileInputStream(new File(pathname));
            FileChannel channel = fin.getChannel();

            int capacity = 100;// 字节
            ByteBuffer bf = ByteBuffer.allocate(capacity);
            System.out.println("限制是:" + bf.limit() + "容量是:" + bf.capacity() + "位置是:" + bf.position());
            int length = -1;

            fos = new FileOutputStream(new File(filename));
            FileChannel outchannel = fos.getChannel();


            while ((length = channel.read(bf)) != -1) {

                //将当前位置置为limit,然后设置当前位置为0,也就是从0到limit这块,都写入到同道中
                bf.flip();

                int outlength = 0;
                while ((outlength = outchannel.write(bf)) != 0) {
                    System.out.println("读," + length + "写," + outlength);
                }

                //将当前位置置为0,然后设置limit为容量,也就是从0到limit(容量)这块,
                //都可以利用,通道读取的数据存储到
                //0到limit这块
                bf.clear();

            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (fin != null) {
                try {
                    fin.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (fos != null) {
                try {
                    fos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

}

 

nio实现逐行读取文件

package com.haha.demo.nio;

import java.io.*;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;


public class NioReadLine {
	public static void main(String[] args) throws Exception {
		//指定读取文件所在位置
		File file = new File("d://read.txt");
		FileChannel fileChannel = new RandomAccessFile(file,"r").getChannel();
//		FileChannel fileChannel = new FileInputStream(file).getChannel();
		ByteBuffer byteBuffer = ByteBuffer.allocate(10);
		//使用temp字节数组用于存储不完整的行的内容
		byte[] temp = new byte[0];
		long startTime = System.currentTimeMillis();
		while(fileChannel.read(byteBuffer) != -1) {
			byte[] bs = new byte[byteBuffer.position()];
			byteBuffer.flip();
			byteBuffer.get(bs);
			byteBuffer.clear();
			int startNum=0;
			//判断是否出现了换行符,注意这要区分LF-\n,CR-\r,CRLF-\r\n,这里判断\n
			boolean isNewLine = false;
			for(int i=0;i < bs.length;i++) {
				if(bs[i] == 10) {
					isNewLine = true;
					startNum = i;
				}
			}
			if(isNewLine) {
				//如果出现了换行符,将temp中的内容与换行符之前的内容拼接
				byte[] toTemp = new byte[temp.length+startNum];
				System.arraycopy(temp,0,toTemp,0,temp.length);
				System.arraycopy(bs,0,toTemp,temp.length,startNum);
//				System.out.println(new String(toTemp));
				//将换行符之后的内容(去除换行符)存到temp中
				temp = new byte[bs.length-startNum-1];
				System.arraycopy(bs,startNum+1,temp,0,bs.length-startNum-1);
				//使用return即为单行读取,不打开即为全部读取
//                return;
			} else {
				//如果没出现换行符,则将内容保存到temp中
				byte[] toTemp = new byte[temp.length + bs.length];
				System.arraycopy(temp, 0, toTemp, 0, temp.length);
				System.arraycopy(bs, 0, toTemp, temp.length, bs.length);
				temp = toTemp;
			}

		}
		if(temp.length>0) {
			System.out.println(new String(temp));
		}
		long endTime = System.currentTimeMillis();
		System.out.println(endTime-startTime);

	}
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
可以使用Java中的BufferedReader类来逐读取文件内容。下面是一个示例程序,演示了如何使用BufferedReader逐读取文件内容: ```java import java.io.BufferedReader; import java.io.FileReader; import java.io.IOException; public class ReadFileLineByLineUsingBufferedReader { public static void main(String\[\] args) { BufferedReader reader; try { reader = new BufferedReader(new FileReader("文件路径")); String line = reader.readLine(); while (line != null) { System.out.println(line); line = reader.readLine(); } reader.close(); } catch (IOException e) { e.printStackTrace(); } } } ``` 另外,还可以使用Java 8中的Files类来实现按读取文件的功能。示例如下: ```java import java.io.IOException; import java.nio.file.Files; import java.nio.file.Paths; import java.util.List; public class ReadFileLineByLineUsingFiles { public static void main(String\[\] args) { try { List<String> lines = Files.readAllLines(Paths.get("文件路径")); for (String line : lines) { System.out.println(line); } } catch (IOException e) { e.printStackTrace(); } } } ``` 以上是两种常用的按读取文件的方法。你可以根据自己的需求选择适合的方法来读取文件。 #### 引用[.reference_title] - *1* [Java读取文件](https://blog.csdn.net/qq_30436011/article/details/127488031)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^control,239^v3^insert_chatgpt"}} ] [.reference_item] - *2* [Java读取文件文本内容](https://blog.csdn.net/qq_36433289/article/details/127959932)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^control,239^v3^insert_chatgpt"}} ] [.reference_item] - *3* [Java读取写入文件](https://blog.csdn.net/oh_coding/article/details/129174474)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^control,239^v3^insert_chatgpt"}} ] [.reference_item] [ .reference_list ]

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值