java - 如何在 Android 中从 .txt 文件读取阿拉伯文本

标签 java android arabic

我正在尝试读取具有阿拉伯语文本的文件,然后我需要将读取的文本放置在 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/

相关文章:

java - Spring Boot 不会在 Postgres 中创建表

java - 我可以用什么来在 Java 中设置 cookie?

java - Android studio 在 java class/findViewById 中添加 admob 错误

Android ViewPager、Fragments 和 AsyncTask。如何在方向更改时保留 AsyncTask 的状态?

java - 致命异常 : AsyncTask #1 java. lang.RuntimeException:执行 doInBackground() 错误时发生错误

sql - 如何在sql数据库中插入阿拉伯字符?

iphone - 如何在我的 iPhone 应用程序中显示自定义阿拉伯字体?

java - Mockito Spy - 部分模拟不起作用?

java - 在jar文件中隐藏一些类文件或包

swift - 让 Str = 字符串(格式 : "لديك d٪ ثانية متبقية للاتصال", 秒)