<BIO>以字节的方式(写入,读取)文本,以字符的方式(写入,读取)文本和<NIO>的写入,读取...

package v2ch01.textFile;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.io.Reader;
import java.io.UnsupportedEncodingException;
import java.util.Scanner;

import org.junit.Test;

public class FileTest {


	/**
	 * 以字符的方式写入文本
	 * @throws FileNotFoundException
	 * @throws UnsupportedEncodingException
	 */
	@Test
	public  void writeWenBen() throws FileNotFoundException, UnsupportedEncodingException {

		PrintWriter out = new PrintWriter(new File("e://test.txt"),"utf-8");
		out.write("abcde");
//		out.flush();
		out.close();
		
	}
	
	/**
	 * 以字符的方式读取文本
	 * @throws FileNotFoundException
	 */
	@Test
	public void readWenBen() throws FileNotFoundException{
		
		Scanner scanner = new Scanner(new FileInputStream(new File("e://test.txt")), "utf-8");
		while(scanner.hasNext())
			System.out.println(scanner.nextLine());
		
	}
	
	
	/**
	 * 以字节的方式写入文本
	 * @throws FileNotFoundException
	 */
	@Test
	public void writeByte() throws FileNotFoundException{
		
		OutputStream outputStream = new FileOutputStream(new File("e://test.txt"));
		String str = "I LOVE YOU EVE ";
		char[] ch = str.toCharArray();
//		char[] ch = {'a','b','c','d'};
		for (char c : ch) {
			try {
				outputStream.write(c);
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		try {
			outputStream.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	/**
	 * 以字节的方式读取文本
	 */
	@Test
	public void readByte(){
		
		try {
			InputStream inputStream = new BufferedInputStream(new FileInputStream("e://test.txt"));
			int i=0;
			StringBuilder builder = new StringBuilder();
			while((i=inputStream.read())!=-1){
				
				
				builder.append((char)i);
			}
			System.out.println(builder.toString());
			inputStream.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
		
	}
}

java NIO从一个文件写到另一个文件

    /**
     *通道之间的数据传输
     * transferFrom()方法将数据源从通道传输到FileChannel中
     * @throws IOException
     */
    @Test
    public void transferFrom() throws IOException{
        
        RandomAccessFile fromFile = new RandomAccessFile("e://1.txt", "rw");
        FileChannel fromChannel = fromFile.getChannel();
        
        RandomAccessFile toFile = new RandomAccessFile("e://2.txt", "rw");
        FileChannel toChannel = toFile.getChannel();
        
        long position = 0;
        long count = fromChannel.size();
        
        toChannel.transferFrom(fromChannel, position, count);
    }
    
    /**
     * transferTo()方法将数据从FileChannel传输到其他的channel中
     * @throws IOException
     */
    @Test
    public void transferTo() throws IOException{
        
        RandomAccessFile fromFile = new RandomAccessFile("e://1.txt", "rw");
        FileChannel fromChannel = fromFile.getChannel();
        
        RandomAccessFile toFile = new RandomAccessFile("e://2.txt", "rw");
        FileChannel toChannel = toFile.getChannel();
        
        long position=0;
        long count = fromChannel.size();
        
        fromChannel.transferTo(position, count, toChannel);
    }
    

Java NIO读取文件(可能中文输出乱码)

/**
     * FileChannel无法设置为非阻塞模式,总是运行在阻塞模式下
     * @throws IOException 
     */
    @Test
    public void testReadFromChannel() throws IOException{
        
        Charset charset = Charset.forName("utf-8");
        
        RandomAccessFile file = new RandomAccessFile(new File("e://2.txt"), "rw");
        FileChannel channel = file.getChannel();
        
        ByteBuffer buf = ByteBuffer.allocate(40000);
        int byteRead = channel.read(buf);
        
        StringBuilder sb = new StringBuilder();
        
        while(byteRead!=-1){
            
            buf.flip();
            while(buf.hasRemaining()){
                sb.append((char)buf.get());
            }
            buf.clear();
            byteRead = channel.read(buf);
        }
        
        System.out.println(sb.toString());
        
        
    }

Java NIO写数据到文件

/**
     * 向FileChannel中写数据
     * @throws IOException 
     */
    @Test
    public void testWriteToChannel() throws IOException{
        
        @SuppressWarnings("resource")
        RandomAccessFile file = new RandomAccessFile("e://2.txt", "rw");
        FileChannel channel = file.getChannel();
        String newData = "New String to write to 我是阿凡达 ..... "+System.currentTimeMillis();
        ByteBuffer buf = ByteBuffer.allocate(1024);
        buf.clear();
        
        buf.put(newData.getBytes());
        buf.flip();
        
        while(buf.hasRemaining()){
            channel.write(buf);
        }
        
        channel.close();
    }

 

 

 

转载于:https://my.oschina.net/projerry/blog/671396

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值