我一直在做一个项目,我的文件已保存在内部存储中。我已经观看了多个有关如何读取文件的视频。但是没有任何帮助我读取此目录下的文件。这是我目前得到的所有 java 代码。
public class MainActivity2 extends AppCompatActivity {
TextView text_box;
Button b_show;
float x1,y1,x2,y2;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main2);
b_show = (Button) findViewById(R.id.buttonShow);
text_box = (TextView) findViewById(R.id.textView2);
b_show.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String text = "";
try{
InputStream is = getAssets().open("Scores.txt");
int size = is.available();
byte[] buffer = new byte[size];
is.read(buffer);
is.close();
text = new String(buffer);
} catch(IOException e) {
e.printStackTrace();
}
text_box.setText(text);
}
});
}
public boolean onTouchEvent(MotionEvent touchEvent) {
switch(touchEvent.getAction()){
case MotionEvent.ACTION_DOWN:
x1 = touchEvent.getX();
y1 = touchEvent.getY();
break;
case MotionEvent.ACTION_UP:
x2 = touchEvent.getX();
y2 = touchEvent.getY();
if(x1 < x2) {
Intent i = new Intent(MainActivity2.this, MainActivity.class);
startActivity(i);
}
break;
}
return false;
}
答案 0 :(得分:0)
我已经想通了。而不是使用 Inputstream 作为它的基础。我使用了 File Inputstream 和 InputStreamReader。这是整个@override 的代码以提供帮助。
@Override
public void onClick(View v) {
String text = "";
try{
FileInputStream fileIn = openFileInput("Scores.txt");
InputStreamReader InputRead = new InputStreamReader(fileIn);
char[] inputBuffer = new char[READ_BLOCK_SIZE];
String s = "";
int charRead;
while((charRead = InputRead.read(inputBuffer)) > 0) {
String readstring = String.copyValueOf(inputBuffer, 0, charRead);
s += readstring;
}
InputRead.close();
text_box.setText(s);
} catch(IOException e) {
e.printStackTrace();
}
}