NIOの簡単なファイル読み取りと書き込みの例

1038 ワード

public static void copyFile() throws Exception {
		String infile = "C:\\src.txt";
		String outfile = "C:\\copy0.txt";

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

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

		//      
		ByteBuffer buffer = ByteBuffer.allocate(1024);

		long startTime = System.currentTimeMillis();
		//         
		for (int i = 0; i < 2000; i++) {
			while (true) {
				// clear       ,           
				buffer.clear();

				//                        position    
				int r = fcin.read(buffer);

				// read          ,    ,            ,   -1
				if (r == -1) {
					fcin.position(0);//  
					break;
				}

				// flip                      
				buffer.flip();

				//               
				fcout.write(buffer);
			}
		}
		System.out.println("NIO waste time:"+(System.currentTimeMillis()-startTime));
		
		fin.close();
		fout.close();
	}