碎片化中使用textview读取文件
时间: 2024-05-16 12:19:09 浏览: 17
在Android中,你可以使用TextView来读取并显示文件内容。下面是一个简单的示例代码,演示如何从文件中读取文本并将其显示在TextView中:
```java
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
public class MainActivity extends AppCompatActivity {
private TextView textView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textView = findViewById(R.id.textView);
// 读取文件
String fileContent = readFileContent("file.txt");
// 将文件内容显示在TextView中
textView.setText(fileContent);
}
private String readFileContent(String fileName) {
File file = new File(getFilesDir(), fileName);
StringBuilder content = new StringBuilder();
try {
FileReader fileReader = new FileReader(file);
BufferedReader bufferedReader = new BufferedReader(fileReader);
String line;
while ((line = bufferedReader.readLine()) != null) {
content.append(line).append("\n");
}
bufferedReader.close();
} catch (IOException e) {
e.printStackTrace();
}
return content.toString();
}
}
```
上述代码假设你有一个名为`file.txt`的文本文件存储在应用的内部存储目录中(`getFilesDir()`)。你可以根据自己的需求修改文件名和文件路径。在此例中,我们将文件内容读取到一个字符串中,并将其设置为TextView的文本。
记得在你的布局文件(`activity_main.xml`)中添加一个TextView控件:
```xml
<TextView
android:id="@+id/textView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:padding="16dp"
android:textSize="16sp" />
```
这样,你就可以使用TextView来读取并显示文件内容了。