【问题标题】:How to read/write String from/to .txt?如何从/向.txt读取/写入字符串?
【发布时间】:2011-12-22 02:23:05
【问题描述】:

我在一个文本文件中有一些文本。我想从文件中读取它(第一个字符串 - 文件中的第一行等),用它做一些事情,然后写入另一个文本文件。

怎么做?

【问题讨论】:

  • 恕我直言,如果您添加之前尝试过的内容,您的问题将会得到更好的接收
  • 但是我没有学习 Java。我今天只需要一个程序。仅此而已。
  • @Артём Царионов:所以你想在不知道如何使用的情况下使用 Java?祝你好运!
  • 也许吧。我怀疑有人愿意这样做。所以我尽我所能。

标签: java file io


【解决方案1】:

Apache Commons IOUtils:

  String contents = FileUtils.readFileToString(file, "UTF-8");
  FileUtils.writeStringToFile(file, contents, "UTF-8");

了解内部实现方式的最佳方法(如果您感兴趣的话)是查看the source code 了解这两种方法。

【讨论】:

  • 虽然可能是正确的(我没有赞成也没有反对),但我认为连基本 Java I/O 都不了解的人不会熟悉 Apache Commons™ 库,也不知道如何下载它并使其与 OP 的其余代码一起使用。
  • 没错,但不应该让任何人遭受低级 Java I/O API 的折磨。并且了解如何查找和使用 jar 文件非常重要。
【解决方案2】:

java.util.Scanner -> 使用它从文件中读取内容(还有很多其他方法,其他人提到过,但我发现这是最简单的一种。)

java.io.PrintWriter -> 用于写入文件(其他方式也可以,如上所述)

【讨论】:

  • 请点击超链接,我忘了添加但@Jeffrey 添加了它,感谢他...
  • 它看不到我的文件。(NetBeans) Scanner sc=new Scanner(new File("test.txt"));
  • 使用完整路径,如“\path\to\folder\filename.txt”
  • printwriter 总是 PrintWriter filer=new PrintWriter("C:\\Users\\Чак\\Documents\\NetBeansProjects\\JavaApplication1\\src\\test1.txt"); 给我“filenotfoundexception”,即使是扫描仪看到的文件。
【解决方案3】:

您必须按照其他人所说的去做。但是这里我会稍微详细一点,并提供一些代码示例。

打开和读取文件:

String fileName = "paper.txt"; // file to be opened

try {
    Scanner fileData = new Scanner(new File(fileName));

    while(fileData.hasNextLine()){
        String line = fileData.nextLine();
        line = line.trim();


        if("".equals(line)){
            continue;
        } // end if

    } // end while

    fileData.close(); // close file
}  // end try

catch (FileNotFoundException e) {
    // Error message    
} // end catch

要写入文本文件,您可以使用以下代码:

boolean fileOpened = true;

try {
    PrintWriter toFile = new PrintWriter("paper.txt");
} // end try

catch (FileNotFoundException e) {
       fileOpened = false;      
    // Error Message saying file could not be opened        
} // end catch

if(fileOpened){
    toFile.println("String to be added to the file");
    toFile.close();
} // end if

我希望这能帮助您解决问题。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-05-12
    • 2012-12-31
    • 1970-01-01
    • 1970-01-01
    • 2017-09-20
    • 1970-01-01
    • 2023-03-19
    相关资源
    最近更新 更多