0

我正在尝试将一些数据写入内部存储。问题是当我阅读它时。它什么也不读。Logcat 说它在里面写了一些东西。但是当我读到它时,Log cat 说它是空的。这是我的文件管理器:

public class FileManager {  
    File dir;
    File driveFile;
    BufferedWriter writer=null;
    BufferedReader reader=null;

    public FileManager(Context context,String name){
        dir = new File(context.getFilesDir(),"drives");
        dir.mkdirs();
        driveFile = new File(dir,name+".txt");
        Log.d("FileManager",driveFile.getAbsolutePath());
    }

    public void open() throws IOException{
        writer = new BufferedWriter(new FileWriter(driveFile));
        reader = new BufferedReader(new FileReader(driveFile));
    }

    public void close() throws IOException{
        writer.close();
        reader.close();
    }

    public boolean writeTrackPoints(Drive drive){
        TrackPoint [] trackPoints=drive.getTrackPoints();
        Log.d("FileManager", "writing....");
        for(int i=0;i<trackPoints.length;i++){
            try {
                String line = trackPoints[i].getParsingString()+"\r\n";
                writer.write(line);
                writer.flush();
                Log.d("FileManager", "Writing" + line);
            } catch (IOException e) {
                return false;
            }           
        }       
        return true;
    }

    public boolean readTrackPoints(Drive drive){
        String line=null;
        Log.d("FileManager", "reading....");
        try {
            while((line = reader.readLine())!=null){
                Log.d("FileManager", "Reading: "+line);
                drive.addTrackPoint(new TrackPoint(line));
            }
        } catch (IOException e) {
            Log.d("FileManager", e.getMessage());
            return false;
        }       
        return true;
    }
}

我无法检查文件是否为空,因为我的设备没有植根。我认识到它在阅读时不会进入。我一次打开两个流不是问题吗?

4

1 回答 1

1

我已经解决了。问题在于方法打开/关闭。也许不可能同时打开两个流。这是编辑过的文件管理器:

public class FileManager {

    File dir;
    File driveFile;
    BufferedWriter writer=null;
    BufferedReader reader=null;
    public FileManager(Context context,String name){
        dir = new File(context.getFilesDir(),"drives");
        dir.mkdirs();
        driveFile = new File(dir,name+".txt");
        Log.d("FileManager",driveFile.getAbsolutePath());
    }

    public void writeTrackPoints(Drive drive) throws IOException{
        writer = new BufferedWriter(new FileWriter(driveFile));
        TrackPoint [] trackPoints=drive.getTrackPoints();
        for(int i=0;i<trackPoints.length;i++){
            String line = trackPoints[i].getParsingString()+"\r\n";
            writer.write(line);
            writer.flush();
        }
        writer.close();
    }

    public void readTrackPoints(Drive drive) throws IOException{
        reader = new BufferedReader(new FileReader(driveFile));
        String line=null;
        while((line = reader.readLine())!=null){
            drive.addTrackPoint(new TrackPoint(line));
        }
        reader.close();
    }
}
于 2013-09-28T11:40:34.263 回答