简体   繁体   English

从文件读取字节?

[英]Reading bytes from a file?

I need to read some data until file is opened at different times, but I'm not sure if pointer to data that have not been read yet is automatic increased? 我需要读取一些数据,直到在不同时间打开文件为止,但是我不确定是否自动增加了指向尚未读取的数据的指针?

My method: 我的方法:

//method for copy binary data from file to binaryDataBuffer
    void readcpy(String fileName, int pos, int len) {       
        try {                                              
            File lxDirectory = new File(Environment.getExternalStorageDirectory().getPath() + "/DATA/EXAMPLE/");

            File lxFile = new File(lxDirectory, (fileName);

            FileInputStream mFileInputStream = new FileInputStream(lxFile);

            mFileInputStream.read(binaryDataBuffer, pos, len);
         }  
        catch (Exception e) {
            Log.d("Exception", e.getMessage());             
        }
    }  

So, if I call this method first time and read and save 5 bytes for example, will be on next call of the method read out bytes from 5th byte? 那么,例如,如果我第一次调用此方法并读取并保存5个字节,那么在下一次调用该方法时会从第5个字节中读出字节吗? I don't close file after reading. 阅读后我没有关闭文件。

When you create an InputStream (because a FileInputStream is an InputStream ), the stream is created anew each time, and starts at the beginning of the stream (therefore the file). 创建InputStream (因为FileInputStreamInputStream ),每次都会重新创建该流,并从该流的开头(因此是文件)开始。

If you want to read from where you left off the last time, you need to retain the offset and seek -- or retain the initial input stream you have opened. 如果要从上次中断的地方开始读取,则需要保留偏移量并查找-或保留已打开的初始输入流。

While you can seek into a stream (using .skip() ), it is in any event NOT recommended to reopen each time, it is costly; 尽管您可以使用( .skip() )来查找流,但是无论如何都不建议每次都重新打开它,但这样做代价高昂; also, when you are done with a stream, you should close it: 同样,在完成流后,应将其关闭:

// with Java 7: in automatically closed
try (InputStream in = ...;) {
    // do stuff
} catch (WhateverException e) {
    // handle exception
}

// with Java 6
InputStream in = ...;
try {
    // do stuff
} catch (WhateverException e) {
    // handle exception
} finally {
    in.close();
}

Try this code: 试试这个代码:

public String getStringFromFile (String filePath) throws Exception {    
    File fl = new File(filePath);
    FileInputStream fin = new FileInputStream(fl);
    BufferedReader reader = new BufferedReader(new InputStreamReader(fin));
    StringBuilder sb = new StringBuilder();

    String line = null;
    while ((line = reader.readLine()) != null) {
        sb.append(line).append("\n");
    }
    String ret = sb.toString();

    //Make sure you close all streams.
    fin.close();  
    reader.close();

    return ret;
}

我找到RandomAccessFile,它具有我需要的偏移量。

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

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