我正在尝试读取具有阿拉伯语文本的文件,然后我需要将读取的文本放置在 TextView 中..
以下是我尝试过的代码:
public static String readRawFile(Context ctx, int resId) throws UnsupportedEncodingException {
InputStream inputStream = ctx.getResources().openRawResource(resId);
InputStreamReader isr = new InputStreamReader(inputStream, "UTF-8");
BufferedReader reader = new BufferedReader(isr);
String line;
StringBuilder text = new StringBuilder();
try {
while ((line = reader.readLine()) != null) {
text.append(line);
Log.e("Line Read", line);
text.append('\n');
}
} catch (IOException e) {
return null;
}
return text.toString();
}
但是我读取的文件如下
��(P3�EP ��qDDGP ��qD1QN-�EN@pFP ��qD1QN-PJEP ����
我应该如何读取文件,以便读取的文本是阿拉伯语
最佳答案
尝试仅使用 Bufferreader,有了它我可以同时阅读阿拉伯语和英语单词。而且您不需要 UT-8 编码。 我希望这对您有帮助:
public static void readArabic(String path) throws FileNotFoundException {
try(BufferedReader red = new BufferedReader(new FileReader(path));) {
String out;
while ((out = red.readLine()) != null){
System.out.println(out);
}
} catch (IOException e) {
e.printStackTrace();
}
}
这是主要方法:
public static void main(String[] args) throws FileNotFoundException {
String path1 = "/Users/addodennis/Desktop/Projects/HotelReservation/src/Data/testAra";
readArabic(path1);
}
这是输出: 我刚刚从维基百科页面复制了一些阿拉伯文本。
阿拉伯语或阿拉伯语或阿拉伯语 ’ī (هََِِِь) 或 alifbā’ī (ََِفََِِْف) 巴布亚新几内亚 巴布亚新几内亚 ????????????????????????????????????????????????????????????????????????????????????????????????????????????
如果您仍然想使用 StringBuilder 那么您也可以这样做:
public static String readArabic(String path) throws FileNotFoundException {
StringBuilder add = new StringBuilder();
try(BufferedReader red = new BufferedReader(new FileReader(path));) {
String out;
while ((out = red.readLine()) != null){
//System.out.println(out);
add.append(out);
}
} catch (IOException e) {
e.printStackTrace();
}
return String.valueOf(add);
}
关于java - 如何在 Android 中从 .txt 文件读取阿拉伯文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37546034/