Java:简单的文件操作,将用字符表示的16进制数转为对应的2进制内容保存到新文件中...

本文深入探讨了为何大多数编程人员难以晋升为架构师,解析了技能、思维模式和实践经验之间的关键区别,旨在帮助程序员提升自我,迈向高级职位。
package main;
import  java.io.*;

class test{

	private static String hexString = "0123456789abcdef"; 
	
	public static void main(String[] args) throws IOException{
		int argc = args.length;
		if(argc==1){
			String fileInPath = "src/resource/test.txt";
			String fileOutPath = "src/resource/data.txt"; //相对路径
	        PacketsToFile(fileInPath,fileOutPath);
		}else if(argc==2){
			PacketsToFile(args[0],args[1]);//输入绝对路径
		}else{
			System.out.println("输入格式错误");
			System.out.println("先用记事本替换文件中全部的'|'符号,输入的格式java -jar string2hex.jar D://test.txt D://data.txt第一个是原文件,后一个是生成的文件,需要自己先创建文件");
		}
		
	}	
	
	public static void PacketsToFile(String fileInPath,String fileOutPath) throws IOException{
		try{
			String encoding="UTF-8";
			File file=new File(fileInPath);
			File data=new File(fileOutPath);
			
			DataOutputStream os = new DataOutputStream(new FileOutputStream(data));
			if(file.isFile() && file.exists() && data.isFile() && data.exists()){
				InputStreamReader read = new InputStreamReader(
				    new FileInputStream(file),encoding);
				BufferedReader bufferedReader = new BufferedReader(read);
				String lineTxt = null;
				int i = 1,n = 1;
				while((lineTxt = bufferedReader.readLine()) != null ){
					if(i==(4*n-1)){ //取决于文件中数据包的位置,这里是在3,7,11..行
						n++;
						String temp = lineTxt.substring(4,lineTxt.length()).trim();
						String len = Integer.toHexString(temp.length()/2);
						//数据包前加入两个字节的数据包长度
						if(len.length()==1){
							len = "000"+len;
						}else if(len.length()==2){
							len = "00"+len;
						}else if(len.length()==3){
							len = "0"+len;
						}else if(len.length()>4||len.length()==0){
							System.out.println("帧内容异常");
						}
						
						String oneP = len+temp;
						for (int j = 0; j < oneP.length(); j += 2){
							byte oneByte = (byte)((hexString.indexOf(oneP.charAt(j))*16)
							    +(hexString.indexOf(oneP.charAt(j + 1))));
							//把对应的整数转为一个字节
							os.write(oneByte);
						}						
					}
					i++;
				}
				long sizeOfFile = (long) file.length();
				System.out.println("原文件有 "+sizeOfFile*1.0/(1024.0*1024.0)+" MB");
				System.out.println("包含"+(n-1)+"个数据包");
				long sizeOfData = (long) data.length();
				System.out.println("生成文件有 "+sizeOfData*1.0/(1024.0*1024.0)+" MB");
				read.close();
				os.close();
			}else{
				System.out.println("找不到指定的文件,请检查路径");
			}
		}catch (Exception e) {
            System.out.println("读取文件时发生错误出错");
            e.printStackTrace();
        }
	}
}


转载于:https://my.oschina.net/xcxt/blog/364221

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值