一个把String转成byte数组的小程序

本文介绍了一个Java工具类,用于将文件中特定格式的字符串声明转换为字节数组声明,适用于资源文件的编译时优化。通过读取指定文件,解析并替换原有的字符串声明,生成新的字节数组形式的变量声明。

来源:http://www.study-code.com/java/j2se/66420.htm

 

/*
*@类功能:将一个文件中的String声明转换成byte[] 声明
*
*
*@作者:关文柏
*@时间:2006年11月11日
*/

//---------------------------------------------------------------//
//NOTE: Make sure the identifier of variable as same as "inflag_0"
//
//---------------------------------------------------------------//
import java.io.*;
import java.util.*;

public class MakeResource
{
 //Output file declare symbol
 private static final String outflag_0 = " public final static byte[] ";
 private static final String outflag_1 = " = {";
 private static final String outflag_2 = "};";
 private static final String outflag_3 = ",";
 private static final int ch_0 = 0x0d;
 private static final int ch_1 = 0x0a;
 
 //Input file declare symbol
 private static final String inflag_0 = "public final static String"; //' the squence may variety
 private static final char inflag_1 = '"';
 private static final char inflag_2 = ';';
 private static final char inflag_3 = '=';
 private static final char inflag_4 = '/';
 

 //Resource of all string
 private String[] res = null;
 //Names of all string
 private String[] resNames = null;

 //For debug
 private boolean debug = false;
 public MakeResource()
 {
  System.out.println("Please enter the file name:");
  BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
  try{
   doInput(br.readLine());
  
  }catch(Exception e){
   e.printStackTrace();
  }

  doOutput(res,resNames);
  
 }

 public static void main(String[] args)
 {
  new MakeResource();
 }

 private void doInput(String fileName)
 {
  try{
  
   FileInputStream fis = new FileInputStream( new File( fileName ) );
   
   byte[] contents = new byte[ fis.available() ];
   
   fis.read( contents );
   if(debug)
    System.out.println("The file has "+contents.length+" bytes");
   
   char[] declare = inflag_0.toCharArray();
   
   Vector names = new Vector(); //For save variable names
   
   Vector resStr = new Vector(); //For save the variable's content
   
   int x = 0;   //index of all bytes
   
   boolean out = false; //Flag for out of loop

   int variableNum = 0;
   while(!out)
   {
    int counter = 0; //Matching char numbers
    
    int y = 0;   //index of 'declare' array
    if(contents[x]==inflag_4)  //skip a comment line
    {
     boolean out_0 = false;
     while( !out_0 && x+2 < contents.length)
     {
      if( ((int)contents[x+1]!= ch_0) && ((int)contents[x+2]!= ch_1) )
      {
       x++;
      }else
      {
       out_0 = true;
      }
     }
    }
    if(contents[x] == declare[y])
    {

     for(y = 1; y < declare.length  ; y++)
     {
      if(x + 1 < contents.length)
      {
       if(contents[++x]==declare[y])
        counter++;
      }
      else
      {
       out = true;      
      }
     }
    }
    //If some chars begin with "public final static String"
    if(counter==declare.length-1)
    {
     variableNum++;

     if(debug)
      System.out.println("A variable matching at "+x);
     if(x + 1 < contents.length)
      x++;  //skip a space in front of the variable name
     else
     {     
      out = true; 
     }

     StringBuffer avName = new StringBuffer(); //For save the variable name
     
     boolean out_1 = false;
     while( !out_1 && x+1 < contents.length)
     {
      if(contents[++x]!=inflag_3)
      {
       avName.append((char)contents[x]); 
      }else
      {
       out_1 = true;
      }
     }
     names.addElement( avName.toString() );
     
     boolean out_2 = false;
     StringBuffer str = new StringBuffer();  //For save the variable content
     while(!out_2 && x + 1 < contents.length)
     {
      if(contents[++x]==inflag_1)
      {
       boolean out_3 = false;
       while(!out_3 && x + 1 < contents.length)
       {       
        if( contents[++x]!=inflag_2 )
        {
         str.append( (char)contents[x] );
        }else
        {
         out_3 = true;
         out_2 = true;
        }
       }
       
      }
     }
     if(str.length() > 0) 
     str.deleteCharAt( str.length() -1  );  //Delete the last char of content,it is must a ' " '
     resStr.addElement( str.toString() );
     
    }
    counter = 0;  //reset counter

    if(x + 1 < contents.length)
     x++;  //If does not matched any char, move index of all bytes
    else
    {    
     out = true;
    }
   }
   res = new String[resStr.size()];
   //if(debug)
    //System.out.println("//--------------Variable contents--------------//");

   for(int p = 0 ; p < resStr.size(); p++)
   {
    res[p] = (String)resStr.elementAt(p);
    //if(debug)
     //System.out.println( (String)resStr.elementAt(p) );   
   }
   if(debug)
    System.out.println("");
   resNames = new String[names.size()];
   if(debug)
    System.out.println("//--------------Variable names--------------//");
   for(int q = 0 ; q < names.size(); q++)
   {
    resNames[q] = (String)names.elementAt(q);
    if(debug)
     System.out.println( (String)names.elementAt(q) );   
   }

   if(debug)
    System.out.println(variableNum+" variables has been finded!");

  }catch(Exception ex)
  {
   ex.printStackTrace();
  }
 }

 private void doOutput(String[] res,String[] names)
 {
  int strLength = 0;
  if((res==null)||(names==null))
  {
   System.out.println("Array does not initial");
   return;
  }
  if( (strLength = res.length ) != names.length )
  {
   System.out.println("Current array not correct");
   return;
  }
  try
  {
  FileWriter fw = new FileWriter( new File(".","result.txt") ); //A file named 'result' for save the content
  for(int m =0 ; m < strLength; m++)
  {
   byte[] b = res[m].getBytes();
   fw.write( outflag_0, 0, outflag_0.length() ); //write the identifier
   fw.write( names[m], 0, names[m].length() );  //write variable name
   fw.write( outflag_1, 0, outflag_1.length() ); //'={'
   for(int z = 0 ; z < b.length; z++)
   {
    fw.write( new Integer((int)b[z]).toString() ); //write bytes with int format
    if(z<b.length-1)
    fw.write( outflag_3, 0, outflag_3.length() ); //','
   }
   fw.write( outflag_2, 0, outflag_2.length() ); //'};'
   fw.write( ch_0 );  //write a enter for new line
   fw.write( ch_1 );
  }

  fw.close();
  System.out.println("Output successfully!!!!!");
  }catch(Exception e)
  {
   e.printStackTrace();
  }
  
 } 

转载于:https://www.cnblogs.com/kangshifu/archive/2008/11/08/1329567.html

### 回答1: 将byte数组换为图片需要使用IO流进行读写操作。可以使用JavaByteArrayInputStream类将byte数组读入到输入流中,然后使用ImageIO类的read方法读取图像文件,最后使用ImageIO类的write方法将读取到的图像文件写入到输出流中。 示例代码如下: ``` import java.io.ByteArrayInputStream; import java.io.File; import java.io.IOException; import javax.imageio.ImageIO; import java.awt.image.BufferedImage; public class ByteArrayToImage { public static void main(String[] args) { byte[] byteArray = {1,2,3,4,5,6,7,8,9}; BufferedImage image = null; try { ByteArrayInputStream bis = new ByteArrayInputStream(byteArray); image = ImageIO.read(bis); ImageIO.write(image, "jpg", new File("output.jpg")); } catch (IOException e) { e.printStackTrace(); } } } ``` 上面的程序将byte数组换成图片文件并写入到本地的个叫做output.jpg的文件中. 其中, byteArray为要换的byte数组,后面的“jpg”是图片格式, "output.jpg" 是输出文件的路径。 ### 回答2: byte数组换成图片,可以通过以下步骤实现: 1. 首先,我们需要创建个空的BufferedImage对象,用于存储图片的像素数据。 2. 然后,可以使用ImageIO类的read方法,将byte数组换成BufferedImage对象。该方法需要传入ByteArrayInputStream对象作为参数,将byte数组包装成输入流。 3. 接下来,我们可以根据BufferedImage对象的getWidth和getHeight方法,获取图片的宽度和高度。 4. 创建个Graphics对象,通过调用BufferedImage对象的createGraphics方法得到。这个Graphics对象可以用于后续图片的绘制操作。 5. 调用Graphics对象的drawImage方法,将BufferedImage对象绘制到Graphics对象上。 6. 最后,可以通过ImageIO类的write方法,将BufferedImage对象保存为图片文件。该方法需要传入个File对象和个格式字符串作为参数。 7. 如果想要以其他格式保存图片,可以在写入之前使用ImageIO类的setUseCache方法设置为false,并传入其他格式的Writer对象。 通过以上步骤,我们就可以将byte数组换成图片并保存到文件中。 ### 回答3: 将byte数组换为图片需要经过以下几个步骤: 1. 首先,需要获取到byte数组作为输入。这个byte数组通常是从文件、数据库或网络中读取出来的图片数据,它是以字节序列的形式保存的。 2. 接下来,我们需要创建个BufferedImage对象。BufferedImage是Java中处理图片的类,它可以用来生成、修改或合成图片。 3. 然后,我们可以使用ImageIO类的静态方法read来读取byte数组并将其换为BufferedImage对象。这个方法接受个输入流作为参数,由于我们的输入是byte数组,所以我们可以使用ByteArrayInputStream类将byte数组换为输入流。 4. 接下来,我们可以根据BufferedImage对象的宽度和高度创建个Graphics2D对象,并使用其drawImage方法绘制图片。在这步中,我们可以设置图像的大小、颜色、透明度等,以便于我们对图片进行进步的处理。 5. 最后,我们可以使用ImageIO类的静态方法write将BufferedImage对象以指定的格式写入到个输出流中。这个输出流可以是个文件输出流,以将图片保存到本地文件中;也可以是个字节数组输出流,以便于我们将图片数据传输到网络或其他地方。 通过以上步骤,我们可以将byte数组换成图片,并根据需求对图片进行进步的处理和操作。在实际应用中,我们可以根据具体的需求选择合适的图片格式和处理方法,以达到最佳的效果和性能。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值