code_junkie

Java App : Unable to read iso-8859-1 encoded file correctly

Nov 14th, 2011
148
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.47 KB | None | 0 0
  1. File in = new File("myfile.csv");
  2. InputStream fr = new FileInputStream(in);
  3. byte[] buffer = new byte[4096];
  4. while (true) {
  5. int byteCount = fr.read(buffer, 0, buffer.length);
  6. if (byteCount <= 0) {
  7. break;
  8. }
  9.  
  10. String s = new String(buffer, 0, byteCount,"ISO-8859-1");
  11. System.out.println(s);
  12. }
  13.  
  14. System.out.println(java.nio.charset.Charset.availableCharsets());
  15.  
  16. System.out.println((int) s.getCharAt(index));
  17.  
  18. System.out.println("Here's the character: u00f4");
  19.  
  20. BufferedReader br = new BufferedReader(
  21. new InputStreamReader(
  22. new FileInputStream("myfile.csv"), "ISO-8859-1");
  23.  
  24. char[] buffer = new char[4096]; // character (not byte) buffer
  25.  
  26. while (true)
  27. {
  28. int charCount = br.read(buffer, 0, buffer.length);
  29.  
  30. if (charCount == -1) break; // reached end-of-stream
  31.  
  32. String s = String.valueOf(buffer, 0, charCount);
  33. // alternatively, we can append to a StringBuilder
  34.  
  35. System.out.println(s);
  36. }
  37.  
  38. public static void main(String[] args) throws IOException {
  39. byte[] data = { (byte) 0xF4 };
  40. String decoded = new String(data, "ISO-8859-1");
  41. if (!"u00f4".equals(decoded)) {
  42. throw new IllegalStateException();
  43. }
  44.  
  45. // write default charset
  46. System.out.println(Charset.defaultCharset());
  47.  
  48. // dump bytes to stdout
  49. System.out.write(data);
  50.  
  51. // will encode to default charset when converting to bytes
  52. System.out.println(decoded);
  53. }
  54.  
  55. 5554 462d 380a f4c3 b40a
Add Comment
Please, Sign In to add comment