gpt4 book ai didi

java - 如何读取 Android Assets 中的文件

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

我的 Android 遇到问题。我想打开文件,检查它并只返回一个简单的值。

public void setMessageCode(String code){
try {
messageCode = setMsg(code);
} catch (IOException e) {
e.printStackTrace();
}
}

public String setMsg(String messageCode) throws IOException{
String FILE = "src/dialogs.txt", msg;
BufferedReader in = new BufferedReader(new FileReader(FILE)); //IO Exception here
msg = in.readLine();
while(msg!=null){
message = msg.split(",");
for(int i=0; i<message.length; i++)
if(message[i].equals(messageCode)){
in.close();
return message[i++];
}
msg = in.readLine();
}
in.close();
return "Nothing to get";
}

所以 Eclipse 没有发现问题并且工作完美。 ADT 失败。 Dialogs.txt 位于 src/... 中,我检查了这一百万次。该怎么办?

最佳答案

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

import android.app.Activity;
import android.os.Bundle;
import android.view.Menu;

public class MainActivity extends Activity {

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
try {
String first_line = read_file("dialogs.txt");
System.out.print(first_line);
} catch (IOException e) {
e.printStackTrace();
}
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}


public String read_file(String filename) throws IOException {
BufferedReader reader = new BufferedReader(new InputStreamReader(
getAssets().open(filename)));

int i=0;
String line = reader.readLine();
while (line != null) {
if(++i==1)
return line;//only read the first line
line = reader.readLine();
}

reader.close();
return "Nothing to get";
}

}

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

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