代号1的Unicode文件IO [英] Unicode File IO in Codename One

查看:92
本文介绍了代号1的Unicode文件IO的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想读取Unicode文件(UTF-8)并将其写回到另一个文件。

I want to read an Unicode file (UTF-8) and write it back to another file.

我用于读取的代码是,(如代号一中的文本屏幕,如何读取文本文件?

Code I used for reading is, (As in Textscreen in Codename One, how to read text file?)

final String textFile = "/readme.txt";
String text = "";

InputStream in = Display.getInstance().getResourceAsStream(null, textFile);

if (in != null){
    try {
        text = com.codename1.io.Util.readToString(in);
        in.close();
    } catch (IOException ex) {
        System.out.println(ex);
        text = "Read Error";
    }
}

我什至试过

text = com.codename1.io.Util.readToString(in,"UTF-8");

DataInputStream dis = new DataInputStream(in);
text = com.codename1.io.Util.readUTF(dis);

但是我不是Unicode无法读取。

But I am not Unicode is not getting read.

我正在写,

String content = "Some Unicode String";
OutputStream stream = fs.openOutputStream(path + "/" + fileName);
stream.write(content.getBytes());
stream.close();

并尝试过,

DataOutputStream dos = new DataOutputStream(stream);
dos.writeUTF(content);

我观察到生成的文件是ANSI编码的。

I observed generated file is ANSI encode.

更新:解决方案

根据@Shai的回复,

As per @Shai's reply,

阅读:

// For text file in package structure
InputStream in = Display.getInstance().getResourceAsStream(null, "/" + textFile);

// For file in file system
InputStream in = fs.openInputStream(textFile);


if (in != null) {
  try {
      text = com.codename1.io.Util.readToString(in, "UTF-8"); // Encoding
      in.close();
  } catch (IOException ex) {
      text = "Read Error";
  }
}

写:

OutputStream stream = fs.openOutputStream(textFile);
stream.write(content.getBytes("UTF-8"));
stream.close();


推荐答案

readToString()方法以UTF-8编码读取。如果您使用ASCII / ANSI编码之一对文件进行编码,则需要将其修复为UTF-8格式,或为该方法指定特定的编码。

The readToString() method reads with UTF-8 encoding. If you encoded the file in one of the ASCII/ANSI encoding you need to either fix it for UTF-8 or specify the specific encoding to that method.

<$ c DataInputStream 中的$ c> readUT F是完全不同的设计,用于编码流而不是文本文件。 DataInputStream 通常不是为Java中的文本文件设计的,您应该使用 Reader / InputStreamReader 就是这种东西。

readUTF from DataInputStream is something completely different designed for encoded streams and not for text files. DataInputStream in general is not designed for text files in Java, you should be using Reader/InputStreamReader for that sort of stuff.

getBytes()使用平台特定的编码很少是您想要的,您应该使用 getBytes(String)

getBytes() uses the platform specific encoding which is rarely what you want you should use getBytes(String).

这篇关于代号1的Unicode文件IO的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆