Created
July 3, 2014 21:30
-
-
Save amedranogil/4fcd264d71f9871d2abd to your computer and use it in GitHub Desktop.
transform Raw UTF8 input from a file to a Java escaped string.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.io.File; | |
import java.io.FileInputStream; | |
import java.io.IOException; | |
import java.nio.MappedByteBuffer; | |
import java.nio.channels.FileChannel; | |
import java.nio.charset.Charset; | |
/** | |
* @author amedrano | |
* | |
*/ | |
public class UTF8toJavaCode { | |
/** | |
* @param args | |
*/ | |
public static void main(String[] args) { | |
String utf; | |
try { | |
utf = readFile(args[0]); | |
} catch (IOException e) { | |
e.printStackTrace(); | |
utf=""; | |
} | |
// convert the input string to a character array | |
char[] chars = utf.toCharArray(); | |
StringBuilder sb = new StringBuilder(); | |
for (int i = 0; i < chars.length; i++) | |
{ | |
int unipoint = Character.codePointAt(chars, i); | |
if ((unipoint < 32) || (unipoint > 127)) | |
{ | |
StringBuilder hexString = new StringBuilder(); | |
for (int k = 0; k < 4; k++) // 4 times to build a 4-digit hex | |
{ | |
hexString.insert(0, Integer.toHexString(unipoint % 16)); | |
unipoint = unipoint / 16; | |
} | |
sb.append("\\u"+hexString); | |
} | |
else | |
{ | |
sb.append(chars[i]); | |
} | |
} | |
// display the ASCII encoded string | |
System.out.println ("String s = " + sb.toString()); | |
} | |
private static String readFile(String path) throws IOException { | |
FileInputStream stream = new FileInputStream(new File(path)); | |
try { | |
FileChannel fc = stream.getChannel(); | |
MappedByteBuffer bb = fc.map(FileChannel.MapMode.READ_ONLY, 0, fc.size()); | |
/* Instead of using default, pass in a decoder. */ | |
return Charset.defaultCharset().decode(bb).toString(); | |
} | |
finally { | |
stream.close(); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment