如何使用InputStreamReader从Android Studio中的文件中逐行读取

问题描述 投票:-1回答:2

我现在能够读取一个文件,但是我对如何逐行读取字符串以运行我创建的解析器感到困惑。任何的意见都将会有帮助。

public void ReadBtn() {
        char[] inputBuffer = new char[READ_BLOCK_SIZE];
        int charRead;
        String s = "";
        int READ_BLOCK_SIZE = 100;

        //reading text from file
        try {
            FileInputStream fileIn = openFileInput("mytextfile.txt");
            InputStreamReader InputRead = new InputStreamReader(fileIn);
            BufferedReader BR = new BufferedReader(InputRead);

            while((charRead = InputRead.read(inputBuffer)) > 0) {
                // char to string conversion

            String readstring = String.copyValueOf(inputBuffer, 0, charRead);
                s += readstring;
                getContactInfo(s);


            }

            InputRead.close();


        } catch(Exception e) {
            e.printStackTrace();
        }
    }
java android line fileinputstream
2个回答
0
投票

- 试试这段代码。将sdCard路径替换为mytextfile.txt所在的文件路径。

String sdCard = Environment.getExternalStorageDirectory().getAbsolutePath();

    String fileName = "mytextfile.txt";
    String path = sdCard + "/" + MarketPath + "/";

    File directory = new File(path);
    if (directory.exists()) {
        File file = new File(path + fileName);
        if (file.exists()) {
            String myData = ""; // this variable will store your file text
            try {
                FileInputStream fis = new FileInputStream(file);
                DataInputStream in = new DataInputStream(fis);
                BufferedReader br =new BufferedReader(new InputStreamReader(in));
                String strLine;
                while ((strLine = br.readLine()) != null) {
                    myData = myData + strLine;
                }


                in.close();
            } catch (IOException e) {
                e.printStackTrace();
            }

        }
    }

}

0
投票

你可以阅读ArrayList中的所有行:

public void ReadBtn() {
    int READ_BLOCK_SIZE = 100;
    ArrayList<String> linesList = new ArrayList<>();

    // reading text from file
    try {
        FileInputStream fileIn=openFileInput("mytextfile.txt");
        InputStreamReader InputRead= new InputStreamReader(fileIn);
        BufferedReader br = new BufferedReader(InputRead);

        String line = br.readLine();
        while (line != null) {
            linesList.add(line);
            line = br.readLine();
        }

        InputRead.close();

        // here linesList contains an array of strings

        for (String s: linesList) {
            // do something for each line
        }

    } catch (Exception e) {
        e.printStackTrace();
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.