BufferedReader更改读取文件的内容

时间:2019-02-19 13:22:10

标签: java io bufferedreader

我正在尝试读取某些文件,将其解析为我自己的DataType。但是,最初的文件如下所示:

16
12
-----
0;0;0;0;0;0;0;0;0;0;0;0;0;0;0;0
0;2;2;2;2;2;2;2;2;2;2;2;2;2;2;0
0;2;1;1;1;1;1;2;2;1;1;1;1;1;2;0
0;2;1;0;0;0;0;5;5;0;0;0;0;1;2;0
0;2;1;0;2;2;2;2;2;2;2;2;0;1;2;0
0;2;1;0;2;2;2;2;2;2;2;2;0;1;2;0
0;2;1;0;2;2;2;2;2;2;2;2;0;1;2;0
0;2;1;0;2;2;2;2;2;2;2;2;0;1;2;0
0;1;1;0;2;2;2;2;2;2;2;2;0;1;1;0
0;0;0;0;2;2;2;2;2;2;2;2;0;0;0;0
0;2;2;2;2;2;2;2;2;2;2;2;2;2;2;0
0;0;0;0;0;0;0;0;0;0;0;0;0;0;0;0

然后我这样阅读:

try {
    File file = new File(path);
    if (!file.exists()) {
        return new ScreenMap(id, 16, 12);
    }
    FileReader fr = new FileReader(file);
    BufferedReader br = new BufferedReader(fr);
    String line = br.readLine();
    int lineIndex = 0;
    //Map Constants
    ScreenMap result = new ScreenMap(id, 1, 1);
    int width = 1;
    int height = 1;
    while(line != null){
        if(lineIndex == 0){
            width = Integer.parseInt(line);
        }
        else if(lineIndex == 1){
            height = Integer.parseInt(line);
        }
        else if(lineIndex == 2){
            //Create Map
            result = new ScreenMap(id, width, height);
        }
        else if(lineIndex-3 < height){
            int y = lineIndex - 3;
            String[] tiles = line.split(seperatorString);
            for(int x = 0; x < width; x++){
                parseTileOntoMap(x,height-y-1,tiles[x],result);
            }
        }
        lineIndex++;
        line = br.readLine();
    }
    br.close();
    return result;
} catch (IOException e) {
    Logger.logError(e);
}

然后我的文件如下:



-----
 ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; 
 ;;;;;;;;;;;;;;; 
 ; ; ; ;;;;;;;;; ; ; ; 
 ;;; ;;;;;;;;; ;;; 
 ;;; ;;;;;;;;; ;;; 
 ;;; ;;;;;;;;; ;;; 
 ;;; ;;;;;;;;; ;;; 
 ;;; ;;;;;;;;; ;;; 
 ;;; ; ; ; ;;; ; ; ; ;;; 
 ;;;;;;;;;;;;;;; 
 ;;;;;;;;;;;;;;; 
 ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; 

此处在记事本++中打开: an Image because I don't know how the text looks after copy and paste

我尝试使用不同的方法通过InputStreams等初始化BufferedReader。 当我尝试使用BufferedWriter写回文件时,也会发生同样的事情。

文件扩展名(尽管我不知道为什么这么重要)是.ddm

所以我想我想知道为什么会这样,以及如何解决它。

1 个答案:

答案 0 :(得分:2)

在代码的某个点(缺少该点),您正在写入文件。我怀疑您的代码看起来像这样:

for(Integer value:values){
  bufferedWriter.write(value);
}

value视为char,将整数0转换为(char)0。您想将值写为String,所以应该使用

bufferedWriter.write(String.valueOf(value));
相关问题