所以我试图改变每两行都有行号的文本文件的格式,以使其更清晰,更易于阅读。我制作了一个简单的程序,用一个空格替换一行的前三个字符,这三个字符空格就是数字所在的位置。实际的文本直到几个空格才会开始。当我这样做并打印出最终结果时,它会带有一个带有问号的钻石,我假设这是缺少字符的结果。似乎大多数缺少的字符都是撇号符号。如果有人能让我知道如何解决它,我会非常感激:)
public class Conversion {
public static void main(String args[]) throws IOException {
BufferedReader scan = null;
try {
scan = new BufferedReader(new FileReader(new File("C:\\Users\\Nasir\\Desktop\\Beowulftesting.txt")));
} catch (FileNotFoundException e) {
System.out.println("failed to read file");
}
String finalVersion = "";
String currLine;
while( (currLine = scan.readLine()) !=null){
if(currLine.length()>3)
currLine = " "+ currLine.substring(3);
finalVersion+=currLine+"\n";
}
scan.close();
System.out.println(finalVersion);
}
}
答案 0 :(得分:0)
FileReader
,而不是InputStreamReader
。我认为奇怪的字符出现是因为你正在使用错误的编码读取文件。顺便说一句,不要像循环一样在循环中使用+=
。相反,请使用StringBuilder
:
StringBuilder finalVersion = new StringBuilder();
String currLine;
while ((currLine = scan.readLine()) != null) {
if (currLine.length() > 3) {
finalVersion.append(" ").append(currLine.substring(3));
} else {
finalVersion.append(currLine);
}
finalVersion.append('\n');
}