JavaSE-io流-字符字节转换流

JavaSE-io流-字符字节转换流

package io流;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.util.Arrays;

/**
 * 字节字符转换流
 * InputStreamReader
 * OutputStreamWriter
 * 
 * */

public class 字节字符转换流 {

	public static void main(String[] args) {
		try {
			//指定编码形式的 读取文件
			FileInputStream in1 = new FileInputStream("charSet.txt");
			InputStreamReader in2 = new InputStreamReader(in1,"utf-8"); //依赖于别的流
		
			char[] arr = new char[100];
			in2.read(arr);
			
			System.out.println(new String(arr));
		
			in2.close();
			in1.close();
			
			
			
			
			//指定编码形式的存入文件
			String name ="Tom你好世界哈哈哈哈";
			FileOutputStream out1 = new FileOutputStream("charSet2.txt");
			OutputStreamWriter out2 = new OutputStreamWriter(out1,"utf-8");
			
			out2.write(name);
			
			out2.close();
			out1.close();
			
			//-----------练习   --------
			//功能函数
			//1.  给定一个txt文件   copy操作   变成另一指定名称,位置,编码格式的文件  
			fun1("data.txt", "img","1.txt", "gbk");
			
			
			
			
			//功能函数
			//2.   给定一个txt文件   copy操作   变成另一指定名称,位置,编码格式的文件  
			//     在拷贝的时候不要拷贝原始数据   每个字符做个变换
			//                           在原始字符的编码值的基础上  异或 n   
		
		} catch (Exception e) {
			e.printStackTrace();
		}
	

	}

	//功能函数
	//1.  给定一个txt文件   copy操作   变成另一指定名称,位置,编码格式的文件
	public static void fun1(String orgFile, 
							String targetPos,//img/lib/sta.txt
							String targetFile,
							String charsetName) throws Exception{
		
		File org = new File(orgFile);
		File tarDir = new File(targetPos);//目标所在的问价夹
		File tarFile = new File(targetPos+"/"+targetFile);//目标文件
		
		if (org.exists()&&org.isFile()) {
			//看参数2  目标文件夹
			if (!tarDir.exists()) { //若目标文件夹不存在  自动创建
				tarDir.mkdirs();
			}
			
			//看参数3 目标文件是否已经存
			if(tarFile.exists()){
				throw new Exception("参数2+参数3  当前目标 已有同名文件");
			}
			
			//创建新的文件
			tarFile.createNewFile();
			

			FileInputStream in1 = new FileInputStream(org);
			InputStreamReader in2 = new InputStreamReader(in1);
			
			FileOutputStream out1 = new FileOutputStream(tarFile);
			OutputStreamWriter out2 = new OutputStreamWriter(out1,charsetName);
			
			char[] arr = new char[100];  //101
			while (true) {
				int tmp = in2.read(arr,0,100);
				if (tmp==-1) {
					break;
				}
				
				//arr加密处理一下
//				for (int i = 0; i < tmp; i++) {
//					arr[i] = (char) (arr[i] ^ 2);
//				}
				
				out2.write(arr, 0, tmp);
			}
			
			out2.close();
			out1.close();
			
			in2.close();
			in1.close();
			
			
			
		}else{
			throw new Exception("参数1有问题");
		}
		
	}
	
	
	
}

猜你喜欢

转载自blog.csdn.net/pianai_s/article/details/89763831
今日推荐