简体   繁体   English

从assets文件夹中读取文件

[英]read file from the assets folder

I have a large text file that is in the assets folder, and I have a button that reads the file's next line successfully. 我有一个大文本文件位于assets文件夹中,我有一个按钮,可以成功读取文件的下一行。 However, I want to read the previous line in case the user clicks another button. 但是,如果用户单击另一个按钮,我想阅读上一行。

Reading the whole file to memory is not an option. 将整个文件读取到内存不是一种选择。 The file lines are not numbered. 文件行未编号。

InputStream is = getResources().getAssets().open("abc.txt");
String result= convertStreamToString(is);

public static String convertStreamToString(InputStream is)
            throws IOException {
            Writer writer = new StringWriter();
        char[] buffer = new char[2048];
        try {
            Reader reader = new BufferedReader(new InputStreamReader(is,
                    "UTF-8"));
            int n;
            while ((n = reader.read(buffer)) != -1) {
                writer.write(buffer, 0, n);
            }
        } finally {
            is.close();
        }
        String text = writer.toString();
        return text;
}

If you only need to keep track of one previous line, you can do something like the following, keeping track of the previous line through each iteration (I assumed you were using a reader; for this example, BufferedReader ): 如果您只需要跟踪前一行,您可以执行以下操作,跟踪每次迭代的前一行(我假设您使用的是读取器;对于此示例, BufferedReader ):

String previous = null, line; // null means no previous line
while (line = yourReader.readLine()) {
    // Do whatever with line
    // If you need the previous line, use:
    if (yourCondition) {
        if (previous != null) {
            // Do whatever with previous
        } else {
            // No previous line
        }
    }
    previous = line;
}

If you need to keep track of more than one previous line, you may have to expand that into an array, but you will be keeping a huge amount in memory if your file is large--as much as if you'd read the entire file, once you get to the last line. 如果你需要跟踪多个前一行,你可能需要将它扩展为一个数组,但是如果你的文件很大,你将在内存中保留很大的数量 - 就像你读了整个数据一样文件,一旦到达最后一行。

There is no simple way in Java or Android to read the previous line, only the next (as it is easier in file I/O to more forward than backward). 在Java或Android中没有简单的方法来读取前一行,只有下一行(因为文件I / O更容易向前而不是向后)。

One alternative I can think of is to keep a line marker (starting at 0), and as you advance through the lines, increase it. 我能想到的另一个选择是保持一个线标记(从0开始),当你通过线前进时,增加它。 Then, to go backwards, you have to read the file line by line again, until you get to that line minus one. 然后,要向后移动,您必须再次逐行读取文件,直到您到达该行减去一行。 If you need to go backwards, go to that new line minus one, and so on. 如果你需要倒退,请转到新线减1,依此类推。 It would be a heavy operation, most likely, but would suit your needs. 这很可能会是一次繁重的操作,但会满足您的需求。

Edit: If nothing above will work, there is also a method to read in a file backwards , in which you may be able to use to find the previous line by iterating forward. 编辑:如果上面的任何内容都不起作用,那么还有一种向后读取文件的方法 ,在这种方法中,您可以通过向前迭代来查找前一行。 Just an alternative idea, but definitely not an easy one to implement. 只是一个替代的想法,但绝对不是一个容易实现的想法。

public class LoadFromAltLoc extends Activity {  

    //a handle to the application's resources  
    private Resources resources;  
    //a string to output the contents of the files to LogCat  
    private String output;  

    /** Called when the activity is first created. */  
    @Override  
    public void onCreate(Bundle savedInstanceState)  
    {  
        super.onCreate(savedInstanceState);  
        setContentView(R.layout.main);  

        //get the application's resources  
        resources = getResources();  

        try  
        {  
            //Load the file from the raw folder - don't forget to OMIT the extension  
            output = LoadFile("from_raw_folder", true);  
            //output to LogCat  
            Log.i("test", output);  
        }  
        catch (IOException e)  
        {  
            //display an error toast message  
            Toast toast = Toast.makeText(this, "File: not found!", Toast.LENGTH_LONG);  
            toast.show();  
        }  

        try  
        {  
            //Load the file from assets folder - don't forget to INCLUDE the extension  
            output = LoadFile("from_assets_folder.pdf", false);  
            //output to LogCat  
            Log.i("test", output);  
        }  
        catch (IOException e)  
        {  
            //display an error toast message  
            Toast toast = Toast.makeText(this, "File: not found!", Toast.LENGTH_LONG);  
            toast.show();  
        }  
    }  

    //load file from apps res/raw folder or Assets folder  
    public String LoadFile(String fileName, boolean loadFromRawFolder) throws IOException  
    {  
        //Create a InputStream to read the file into  
        InputStream iS;  

        if (loadFromRawFolder)  
        {  
            //get the resource id from the file name  
            int rID = resources.getIdentifier("fortyonepost.com.lfas:raw/"+fileName, null, null);  
            //get the file as a stream  
            iS = resources.openRawResource(rID);  
        }  
        else  
        {  
            //get the file as a stream  
            iS = resources.getAssets().open(fileName);  
        }  

        //create a buffer that has the same size as the InputStream  
        byte[] buffer = new byte[iS.available()];  
        //read the text file as a stream, into the buffer  
        iS.read(buffer);  
        //create a output stream to write the buffer into  
        ByteArrayOutputStream oS = new ByteArrayOutputStream();  
        //write this buffer to the output stream  
        oS.write(buffer);  
        //Close the Input and Output streams  
        oS.close();  
        iS.close();  

        //return the output stream as a String  
        return oS.toString();  
    }  
} 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM