android从2个不同的文件中读取

时间:2017-10-17 22:07:48

标签: java android file-io

在我的Android应用程序中我试图从2个不同的文件设置2个文本视图名称,但由于某种原因,第一个文本视图被设置为第二个文件信息“成分2”,第二个文本视图根本没有显示?我在设置和打开文件的方式上做错了吗?

public class GroceriesActivity extends AppCompatActivity {
    public TextView groceryname1, groceryname2, groceryname3, groceryname4;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_groceries);


        groceryname1 = (TextView) findViewById(R.id.grocery1);
        groceryname2 = (TextView) findViewById(R.id.grocery2);
        groceryname3 = (TextView) findViewById(R.id.grocery3);
        groceryname4 = (TextView) findViewById(R.id.grocery4);

        String message;
        String message2;
        FileInputStream fis1 = null;
        FileInputStream fis2 = null;
        FileInputStream fis3 = null;
        FileInputStream fis4 = null;
        try {
            fis1 = openFileInput("Ingredient1");
        } catch (FileNotFoundException e1) {
            e1.printStackTrace();
        }
        InputStreamReader isr = new InputStreamReader(fis1);
        BufferedReader br = new BufferedReader(isr);
        StringBuffer sb = new StringBuffer();
        try {
            while ((message = br.readLine()) != null) {
                sb.append(message);
            }
        } catch (IOException e1) {
            e1.printStackTrace();
        }
        groceryname1.setText(sb.toString());
        try {
            fis1.close();
        } catch (IOException e) {
            e.printStackTrace();
        }

        try {
            fis2 = openFileInput("Ingredient2");
        } catch (FileNotFoundException e1) {
            e1.printStackTrace();
        }

        InputStreamReader isr2 = new InputStreamReader(fis2);
        BufferedReader br2 = new BufferedReader(isr2);
        StringBuffer sb2 = new StringBuffer();
        try {
            while ((message2 = br2.readLine()) != null) {
                sb2.append(message2);
            }
        } catch (IOException e1) {
            e1.printStackTrace();
        }
        groceryname2.setText(sb2.toString());
        try {
            fis2.close();
        } catch (IOException e) {
            e.printStackTrace();
        }


    }
}

所以tldr我试图将textview1设置为ingredient1,将textview2设置为ingredient2,但是现在textview1被设置为ingredient2而textview2没有被更改

编辑:修复错误后我现在将textview1和textview2设置为第一个成分

1 个答案:

答案 0 :(得分:1)

尝试更改

sb.append(message2);

sb2.append(message2);