在Android中从文件读取数据

时间:2019-07-05 10:39:49

标签: android file

我必须读取手机存储器中文件中存储的一些数据。我只能读到在终端上打印结果时,它只会打印出几行。我的文件包含以下数据:

enter image description here

我使用以下代码读取了此数据:

 File sdcard = Environment.getExternalStorageDirectory();

            //Get the text file
            File file = new File(sdcard,"data.txt");

            //Read text from file
            StringBuilder text = new StringBuilder();

            try {
                BufferedReader br = new BufferedReader(new FileReader(file));
                String line;

                while ((line = br.readLine()) != null) {
                    text.append(line);
                    text.append('\n');
                    System.out.println(line); //print the result on terminal
                }

                br.close();
            }
            catch (IOException e) {
                //You'll need to add proper error handling here
            }

但是在终端中,它不会打印文件的所有行。终端中的结果视图是这样的: enter image description here

在这种情况下,它仅显示最后四个数据,而在其他情况下,它显示所有内容。我不明白为什么。谁能帮我? 预先感谢您的帮助。

2 个答案:

答案 0 :(得分:1)

从循环中删除 import React, {Component} from 'react' import {create} from './api-user.js' class SignUp extends Component { constructor(){ super(); this.state = { username:'', first_name:'', last_name :'', email : '', password :'' } this.clickSubmit = this.clickSubmit.bind(this) } componentWillReceiveProps(nextProps) { console.log("nextProps", nextProps); } componentDidMount(){ console.log("Component did mount") } handleChange = e => { if (e.target.name === "username") { this.setState({ username: e.target.value }); } if (e.target.name === "first_name") { this.setState({ first_name: e.target.value }); } if (e.target.name === "last_name") { this.setState({ last_name: e.target.value }); } if (e.target.name === "email") { this.setState({ email: e.target.value }); } if (e.target.name === "password") { this.setState({ password: e.target.value }); } } clickSubmit = (e) => { e.preventDefault() const data = this.setState({ first_name :this.state.first_name, last_name : this.state.last_name, username : this.state.username, password:this.state.password, email:this.state.email, }) create(data) //i dnt know if this correct or not } ,并在循环外的System.out.println()中写入最终文本

Log.d()

答案 1 :(得分:0)

尝试这个:

...
String line;
while ((line = br.readLine()) != null) { 
   text.append(line);
   text.append('\n');
}
Log.d("YOUR_TAG", line);
...