Java代码实现native2ascii


package fjcanyue.resourceEditor.util;

import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.Reader;
import java.io.Writer;

/**
* native2ascii.exe java code implementation.
*
* @author lshen
* @version 1.0
*/
public class Native2AsciiUtils
{

/**
* Native to ascii string. It's same as execut native2ascii.exe.
*
* @param str
* native string.
* @return ascii string.
*/
public static String native2Ascii( String str )
{
StringBuffer buffer = new StringBuffer( );

try
{
ByteArrayOutputStream fos = new ByteArrayOutputStream( str
.getBytes( ).length );
Writer out = new OutputStreamWriter( fos, "UTF8" );
out.write( str );
out.close( );
ByteArrayInputStream fis = new ByteArrayInputStream( fos
.toByteArray( ) );

InputStreamReader isr = new InputStreamReader( fis, "UTF8" );
Reader in = new BufferedReader( isr );
int ch;

while ( ( ch = in.read( ) ) > -1 )
{
buffer.append( ( char ) ch );
}

in.close( );

return buffer.toString( );
}
catch ( IOException e )
{
e.printStackTrace( );
return null;
}
}

/**
* Another implementation native2ascii by create temp file.
*
* @param str
* native string.
* @return ascii string.
*/
public static String native2AsciiByTempFile( String str )
{
StringBuffer buffer = new StringBuffer( );

try
{
File file = File.createTempFile( "fjcy", "tmp" );
FileOutputStream fos = new FileOutputStream( file );
Writer out = new OutputStreamWriter( fos, "UTF8" );
out.write( str );
out.close( );
FileInputStream fis = new FileInputStream( file );
InputStreamReader isr = new InputStreamReader( fis, "UTF8" );
Reader in = new BufferedReader( isr );
int ch;
while ( ( ch = in.read( ) ) > -1 )
{
buffer.append( ( char ) ch );
}
in.close( );
return buffer.toString( );
}
catch ( IOException e )
{
e.printStackTrace( );
return null;
}
}

/**
* Ascii to native string. It's same as execut native2ascii.exe -reverse.
*
* @param str
* ascii string.
* @return native string.
*/
public static String ascii2Native( String str )
{
String output = ""

char[] ca = str.toCharArray( );
int x;

for ( x = 0; x < ca.length; ++x )
{
char a = ca[x];
if ( ( int ) a > 255 )
{
output += "\\u" + Integer.toHexString( ( int ) a );
}
else
{
output += a;
}
}

return output;
}
}

0 评论:

My Favorites