---
title: "Java 流与文件笔记"
author: "TrueBrian"
date: "2014-10-20T15:52:00Z"
tags: []
slug: "java"
draft: false
lastmod: "2015-03-11T09:47:17Z"
id: 2191267
url: "https://truebrian.iteye.com/blog/2191267"
---

1.嵌套的输入流

```
DataInputStream din = new DataInputStream(new BufferedInputStream(new FileInputStream("1.dat")));
```

这里 需要从一个文件中读入数据，数据是数字类型，FileInputStream 没有读入数字类型的方法，也没有缓存机制，DataInputStream没有从文件中读数据的方法，

因此可以用重重嵌套构造一个新的构造器。

2.文本操作

PrintWriter 和BufferedReader(new FileReader("2.txt"))

一个典型的输入系统是：

```
String line;
while(line = in.readLine() != null){
  do sth;
}
```

然而BufferedReader没有任何读入数字的处理方法，建议使用Scanner来输入文本。

3.read()方法读文件

```
                File f = new File(path);
		InputStream fis = new FileInputStream(f);
		int l = 0;
		byte[] buf = new byte[2];   //只有两个字节的缓冲区
		while((l=fis.read(buf)) != -1){
			System.out.println(new String(buf,0,l));
		}
		System.out.println("length:" + l);
```

读到文件末尾时会返回-1，作为判断条件，缓冲区只有两个字节，即一个中文，这样出来的结果 一个字一行，且 l永远为0。

四.使用nio来读取和写入文件。

在nio中，读取和写入文件都是对缓冲区进行的。读是从缓冲区中读数据，写是向缓冲区中写数据。因此，在读和写之前，总是先要创建一个缓冲区Buffer，

有不同类型的缓冲区，主要的，使用最多的是ByteBuffer，即字节缓冲区。

1.创建缓冲区方法：

```
ByteBuffer buf = ByteBuffer.allocate(1024);
```

2.nio中使用通道来执行读或取得操作。通道是双向的，能读能写，以块为数据单位。通道都是通过输入输出流来获取的，所以输入输出流还是要的，只不过

这里只是为了从它们中获取通道。

从输入输出流中获取channel

```
    FileInputStream fin = new FileInputStream( infile );
    FileOutputStream fout = new FileOutputStream( outfile );

    FileChannel fcin = fin.getChannel();
    FileChannel fcout = fout.getChannel();
```

3.得到了通道和缓冲区，则可以进行文件的读写了。读是使用channe从缓冲区中读，写是使用channel向缓冲区中写。我们使用上面的缓冲区和通道:

```
fcin.read(buf);
fcout.write(buf);
```

这里还要介绍缓冲区的两个方法；

每个缓冲区都有一个容量，一个当前位置。

clear() 清空缓冲区，让缓冲区可以重新使用，位置回0；

flip() 位置回0，这样使用get方法可以对缓冲区进行遍历。

4.一个例子 copyFile 复制文件

```
package com.wlc.nio;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import static java.io.File.separator;

public class CopyFile {

	public static void main(String[] args) throws IOException {
		String path = "C:" + separator + "Users" + separator + "wlc"
				+ separator + "Desktop" + separator + "项目修改点.txt";
		String to = "C:" + separator + "Users" + separator + "wlc"
				+ separator + "Desktop" + separator + "项目修改点2.txt";
		copyFiles(path, to);
	}

	public static void copyFiles(String from, String to) throws IOException {
		FileInputStream in = new FileInputStream(from);
		FileOutputStream out = new FileOutputStream(to);

		FileChannel fcin = in.getChannel();
		FileChannel fout = out.getChannel();

		ByteBuffer buf = ByteBuffer.allocate(1024);

		while (true) {
			buf.clear();
			int r = fcin.read(buf);  //从通道中读数据到缓冲区，读一个buf，下面就写入一个buf
			if (r == -1) {          //如果r = -1,则说明读完数据了，就跳出了
				break;
			}
			buf.flip();        //这里在写之前千万要记住先flip一下，不然指针指到了buf的最后，写出来的为空了
			fout.write(buf);   //将缓冲区中数据写入通道
		}
	}

}
```

5.缓冲区分片

我们可以对一个缓冲区进行分片，所谓分片，即从一个已有的缓冲区中分出一个片段来，实际还是原来那个缓冲区，相当于一部分，或叫子缓冲区。这个

子缓冲区可以用来执行一些特定的操作。

一个缓冲区分片的例子：

```
package com.wlc.nio;

import java.nio.ByteBuffer;

public class T3 {
	public static void main(String[] args) {
		ByteBuffer buf = ByteBuffer.allocate(10);
		for(int i = 0;i < 10;i ++){
			buf.put((byte) i);
		}
		
		buf.position(3);   //分片起始位置
		buf.limit(6);     //分片区的终点位置
		ByteBuffer slice = buf.slice();
		
		for(int i = 0;i < 3;i ++){              //创建的分片位置从0开始算
			int temp = slice.get(i) * 10;   //给每个值乘以10
			slice.put(i, (byte)temp);
		}
		buf.flip();
		buf.limit(buf.capacity());
		while(buf.hasRemaining()){
			System.out.println((int)buf.get());
		}
	}
}
```

运行结果:

0  
1  
2  
30  
40  
50  
6  
7  
8  
9

6.nio scatter/gather 分散和聚合

参考：[点击打开链接](http://www.tuicool.com/articles/rAfQ7r)

参考：http://www.cnblogs.com/rollenholt/archive/2011/09/11/2173787.html[点击打开链接](http://www.cnblogs.com/rollenholt/archive/2011/09/11/2173787.html)