package routines;

import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.channels.ReadableByteChannel;
import java.nio.channels.WritableByteChannel;
import java.nio.charset.Charset;
import java.nio.charset.CharsetDecoder;
import java.nio.charset.CharsetEncoder;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;


public class ConvertEncoding {

	public static void convertToNewEncoding(String decode, String encode, String inPath, String outPath) throws IOException {
		
		Charset fromCode = Charset.forName(decode);
		Charset toCode = Charset.forName(encode);
		
		CharsetDecoder decoder = fromCode.newDecoder();
		CharsetEncoder encoder = toCode.newEncoder();
		
		Path src = Paths.get(inPath);
		Path dst = Paths.get(outPath);
		
		try (ReadableByteChannel source = FileChannel.open(src, StandardOpenOption.READ);
				WritableByteChannel destination = FileChannel.open(dst, StandardOpenOption.CREATE,
						StandardOpenOption.TRUNCATE_EXISTING, StandardOpenOption.WRITE);) {
			ByteBuffer readBytes = ByteBuffer.allocate(4096);
			while (source.read(readBytes) > 0) {
				readBytes.flip();
				destination.write(encoder.encode(decoder.decode(readBytes)));
				readBytes.clear();
			}
		} catch (Exception e) {
			System.out.println(e);
		}
	}
			  	
}
