Java 从文本文件中删除多行
我正在尝试创建一个方法来删除我的txt文件中的一些文本。我首先检查文件中是否存在一个字符串:Java 从文本文件中删除多行,java,Java,我正在尝试创建一个方法来删除我的txt文件中的一些文本。我首先检查文件中是否存在一个字符串: public boolean ifConfigurationExists(String pathofFile, String configurationString) { Scanner scanner=new Scanner(pathofFile); List<String> list=new ArrayList<>();
public boolean ifConfigurationExists(String pathofFile, String configurationString)
{
Scanner scanner=new Scanner(pathofFile);
List<String> list=new ArrayList<>();
while(scanner.hasNextLine())
{
list.add(scanner.nextLine());
}
if(list.contains(configurationString))
{
return true;
}
else
{
return false;
}
}
有人能帮我删除txt文件中的字符串以及字符串前后的行吗?有很多不同的方法可以做到这一点,尽管我这样做的一种方法是先将文件内容逐行读取到字符串数组中(看起来你已经这样做了),然后删除你不想要的数据,并将所需的新信息逐行写入文件 要删除不想要的行之前的行、不想要的行以及不想要的行之后的行,可以执行以下操作:
List<String> newLines=new ArrayList<>();
boolean lineRemoved = false;
for (int i=0, i < lines.length; i++) {
if (i < lines.length-1 && lines.get(i+1).equals(lineToRemove)) {
// this is the line before it
} else if (lines.get(i).equals(lineToRemove)) {
// this is the line itself
lineRemoved = true;
} else if (lineRemoved == true) {
// this is the line after the line you want to remove
lineRemoved = false; // set back to false so you don't remove every line after the one you want
} else
newLines.add(lines.get(i));
}
// now write newLines to file
List newLines=new ArrayList();
布尔lineRemoved=false;
对于(int i=0,i
请注意,这段代码很粗糙,未经测试,但应该可以满足您的需要。有许多不同的方法可以做到这一点,尽管我这样做的一种方法是先将文件内容逐行读取到字符串数组中(看起来您已经这样做了),然后删除不需要的数据,并将所需的新信息逐行写入文件 要删除不想要的行之前的行、不想要的行以及不想要的行之后的行,可以执行以下操作:
List<String> newLines=new ArrayList<>();
boolean lineRemoved = false;
for (int i=0, i < lines.length; i++) {
if (i < lines.length-1 && lines.get(i+1).equals(lineToRemove)) {
// this is the line before it
} else if (lines.get(i).equals(lineToRemove)) {
// this is the line itself
lineRemoved = true;
} else if (lineRemoved == true) {
// this is the line after the line you want to remove
lineRemoved = false; // set back to false so you don't remove every line after the one you want
} else
newLines.add(lines.get(i));
}
// now write newLines to file
List newLines=new ArrayList();
布尔lineRemoved=false;
对于(int i=0,i
请注意,这段代码很粗糙,未经测试,但应该可以帮助您达到需要的程度。不能“从文件中删除行”。唯一的可能是复制文件,而不是在复制时写出不需要的行。当然,你可以删除字符串的一部分,但像Jim一样,我建议不要直接使用文件。无论如何,扫描仪无法直接写入处于只读模式的文件。您可以使用replace或substring methode from java.lang.String从原始文件中获取内容并将其写入新文件是的,我正在这样做:不会“从文件中删除行”。唯一的可能是复制文件,而不是在复制时写出不需要的行。当然,你可以删除字符串的一部分,但像Jim一样,我建议不要直接使用文件。无论如何,扫描仪无法直接写入处于只读模式的文件。您可以使用replace或substring methode from java.lang.String从原始文件中获取内容并将其写入新文件是的,我正在这样做:问题是我有一个字符串,其中包含四行,我必须删除这些行之前的行和这些行之后的行。因此,您只需要剩余的4行内存中有哪些行?也就是说这是file.txt:a b c d e f g h myString=“c\nd\ne\nf”我希望在运行该方法后,file.txt是:a h问题是我有一个字符串,其中包含四行,我必须删除这些行之前的行和这些行之后的行。因此,您只需要剩下的四行,内存中有哪些文件?也就是说这是file.txt:a b c d e f g h myString=“c\nd\ne\nf”我希望在运行该方法之后,file.txt是:a h