繁体   English   中英

写入txt文档java中的特定行

[英]Write to a specific line in a txt document java

我知道已经有一些有关此问题的帖子,但我不理解。 我的问题是我想在txt文档中找到一个带有名称的行,然后将下一行更改为字符串的内容。

这是我尝试的:

public void saveDocument(String name) {

    String documentToSave = textArea1.getText();

    File file = new File("documents.txt");

    Scanner scanner;

    BufferedWriter bw;

    try {

        scanner = new Scanner(file);

        bw = new BufferedWriter(new FileWriter(file));

        while(scanner.hasNextLine()) {

            if(scanner.nextLine().equals(name)) {

                if(scanner.hasNextLine()) bw.write(scanner.nextLine() + "\n");
                bw.write(documentToSave + "\n");
                if(scanner.hasNextLine()) scanner.nextLine();

            }

            if(scanner.hasNextLine()) bw.write(scanner.nextLine() + "\n");

        }

        bw.flush();
        bw.close();

    } catch (IOException e) {

        e.printStackTrace();

    }

}

也许您是这样尝试的:读取文件并将每一行保存在字符串列表中,如果找到要查找的名称,请替换下一行。 然后将列表中的字符串写回到文件中。 例:

public class NewClass {
   public static void main(String[] args) {
      List<String> list = new ArrayList<String>();
      list = readFile("uzochi");
      writeToFile(list);
   }

public static  List<String> readFile(String name){
    List<String> list = new ArrayList<String>();
    try {
        FileReader reader = new FileReader("C:\\users\\uzochi\\desktop\\txt.txt");
        BufferedReader bufferedReader = new BufferedReader(reader);

        String line;
        boolean nameFound = false;

        while ((line = bufferedReader.readLine()) != null) {
            if(line.equalsIgnoreCase(name)){
                nameFound = true;
                System.out.println("searched name: "+line);
            }
                if(nameFound){                        
                    list.add(line);

                    line = bufferedReader.readLine();
                    System.out.println("line to replace: " + line);
                    line = "another string";
                    System.out.println("replaced line: "+line);
                    list.add(line);
                    nameFound = false;
                }
                else{
                    list.add(line);
                }
        }
        reader.close();

    } catch (IOException e) {
        e.printStackTrace();
    }
    return list;
}

public static void writeToFile(List<String> list){
    try {
            FileWriter writer = new FileWriter("C:\\users\\uzochi\\desktop\\txt.txt", false);
            BufferedWriter bufferedWriter = new BufferedWriter(writer);
            for(String s: list){
                bufferedWriter.write(s);
                bufferedWriter.newLine();
            } 

            bufferedWriter.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

}

txt.txt

hallo
hello
hola
uzochi
world
java
print

此代码应读取整个文件,并将行替换为名称。

while(scanner.hasNextLine()) {
    String line = scanner.nextLine();

    if(line.equals(name)) {
        bw.write(documentToSave + "\n");
   } else {
        bw.write(line + "\n");
  } 
}  

该程序将在给定的行之后替换该行。 它需要我们做更多的工作,例如是否可以定义预期的I / O和使用情况。 现在它从文件中读取并重新放置一行,但是也许您想使用行号而不是行内容来标记要替换的行。

import java.io.*;
public class FileLineReplace {
 public static void replaceSelected(String replaceWith, String type) {
  try {
   String input2 = "";
   boolean replace = false;

   String input = "";

   try (BufferedReader br = new BufferedReader(new FileReader("data.txt"))) {
    for (String line;
     (line = br.readLine()) != null;) {
     // process the line.


     System.out.println(line); // check that it's inputted right


     if (replace) {

      line = "*** REPLACED ***";
      replace = false;
     }

     if (line.indexOf("replaceNextLine") > -1) {

      replace = true;
     }


     input2 = input2 += (line + "\n");

    }
    // line is not visible here.
   }






   // check if the new input is right
   System.out.println("----------------------------------" + '\n' + input2);

   //         write the new String with the replaced line OVER the same file
   FileOutputStream fileOut = new FileOutputStream("data.txt");
   fileOut.write(input2.getBytes());
   fileOut.close();

  } catch (Exception e) {
   System.out.println("Problem reading file.");
   e.printStackTrace();
  }
 }

 public static void main(String[] args) {
  replaceSelected("1 adam 20 M", "foobar");
 }
} 

如果运行代码,它将在“ replaceNextLine”行之后替换下一行:

$ java FileLineReplace 
asd
zxc
xcv
replaceNextLine
wer
qwe
----------------------------------
asd
zxc
xcv
replaceNextLine
*** REPLACED ***
qwe

我的测试文件是

asd
zxc
xcv
replaceNextLine
wer
qwe

运行程序后,文件看起来像这样,并且替换了指定行之后的行。

asd
zxc
xcv
replaceNextLine
*** REPLACED ***
qwe

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM