gpt4 book ai didi

java - 如何在android中读取txt文件?

转载 作者:行者123 更新时间:2023-12-01 21:24:28 25 4
gpt4 key购买 nike

package com.example.popword;

import android.app.Activity;
import android.os.Bundle;
import android.widget.TextView;
import java.io.File;
import java.util.Scanner;

public class ReadText1 extends Activity {
TextView textview;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textview = (TextView) findViewById(R.id.textView);
try (Scanner scanner = new Scanner(new File("C:\\Users\\UOU\\Desktop\\word.txt"))) {
while (scanner.hasNext()) {
textview.setText(scanner.nextLine());
}
} catch (Exception e) {
System.err.println("Exception occurred!");
}
}
}

================================================== ===================================== 2019-11-13 20:07:44.224 1004-1004/com.example.popword E/cklee: com.example.popword.ReadText1.printStackTrace(ReadText1.java:29) com.example.popword.ReadText1.onCreate(ReadText1.java:22) android.app.Activity.performCreate(Activity.java:7136) android.app.Activity.performCreate(Activity.java:7127) android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1271) android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2893) android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3048) android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:78) android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:108) android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:68) android.app.ActivityThread$H.handleMessage(ActivityThread.java:1808) android.os.Handler.dispatchMessage(Handler.java:106) android.os.Looper.loop(Looper.java:193) android.app.ActivityThread.main(ActivityThread.java:6669) java.lang.reflect.Method.invoke( native 方法) com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:493) com.android.internal.os.ZygoteInit.main(ZygoteInit.java:858)

最佳答案

您需要将txt文件放入Android项目包中。您可以将其放入:

  • Assets 文件夹然后:
AssetManager am = context.getAssets();
InputStream is = am.open("word.txt");
  • Res 文件夹 ( res/raw ) 然后:

InputStream is = getResources().openRawResource(R.raw.word);

关于java - 如何在android中读取txt文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58835671/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com