Java 如果出现这种情况,请从文件的每一行中删除特定字符

Java 如果出现这种情况,请从文件的每一行中删除特定字符,java,Java,问题出在这里。我的.txt文件中有一些文本,它看起来就像这样: Bee-bee is the voice that Sheep giv- e. Mou-Mou is the voice that Cow gi- ve. Miau-Miau is the voice that Ca- t gives. //Locate the file: File file = new File("/path/to/file.txt"); //Create a temporary file File temp

问题出在这里。我的.txt文件中有一些文本,它看起来就像这样:

Bee-bee is the voice that Sheep giv-
e. Mou-Mou is the voice that Cow gi-
ve. Miau-Miau is the voice that Ca-
t gives.
//Locate the file:
File file = new File("/path/to/file.txt");

//Create a temporary file
File temp = File.createTempFile("file", ".txt", file.getParentFile());

//String I want to remove
String delete = "-";

//open the file, open the tmp file, read the file line by line and replacing signs
for (String line; (line = reader.readLine()) != null;) {
    // ...
}

//Delete the string from the line.    
line = line.replace(delete, "");
程序,我需要读取此文件和连接线。输出(txt.file):

我想我需要这样做:

Bee-bee is the voice that Sheep giv-
e. Mou-Mou is the voice that Cow gi-
ve. Miau-Miau is the voice that Ca-
t gives.
//Locate the file:
File file = new File("/path/to/file.txt");

//Create a temporary file
File temp = File.createTempFile("file", ".txt", file.getParentFile());

//String I want to remove
String delete = "-";

//open the file, open the tmp file, read the file line by line and replacing signs
for (String line; (line = reader.readLine()) != null;) {
    // ...
}

//Delete the string from the line.    
line = line.replace(delete, "");

这里有一个问题,它将输出文件中的“beebee”替换为“beebee”,这不是我想要的。我需要一些构造“如果符号是“-”,下一个符号是回车符,请删除“-”,但我不知道如何编写它。

readLine
返回的字符串将是整行到换行符

i、 e

蜜蜂是羊发出的声音-

因此,您需要测试的是最后一个字符是
-
,如果是,则返回一个子字符串

您可以使用传统的
lastIndexOf
子字符串
endswith
,也可以使用
-$
的正则表达式模式拆分字符串

例如

    String line = "Bee-bee is the voice that Sheep giv-";
    if (line.endsWith("-")) {
        String output = line.substring(0, line.length() -1);
        System.out.println(output);
        // maybe append to a StringBuilder ?
        stringBuf.append (output);
    }

然后可以将这些子字符串附加到StringBuilder中,这样您就可以得到您想要的整个字符串。

您可以将回车符放在如下字符串中:
“\r”
。通常情况下,一行以新行结尾:
“\n”
。如果此答案满足您的需要,请投票并/或接受此答案