在 Java 中读取和写入 .txt 文件

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15801528/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-31 20:54:18  来源:igfitidea点击:

Reading and Writing to a .txt file in Java

javafiletext

提问by user2242998

Here is my prompt for the assignment: Your program needs to read the information from a text file instead of using a scanner to read from command line. Your program also needs to write the messages into a text file instead of showing the messages on the screen.

这是我的作业提示:您的程序需要从文本文件中读取信息,而不是使用扫描仪从命令行读取信息。您的程序还需要将消息写入文本文件而不是在屏幕上显示消息。

I have the code written and running for it to prompt using the CLI. However, I have absolutely no idea how to change the code utilizing a text file. Can someone please explain this to me?

我已经编写并运行了代码,以便使用 CLI 进行提示。但是,我完全不知道如何使用文本文件更改代码。有人可以向我解释一下吗?

Code so far:

到目前为止的代码:

import java.util.*;

public class parallelArrays {

    public static void main(String[] args) {
       String[] names;
       int[] exam1Grades;
       int[] exam2Grades;
       int n, sum1, sum2;
       double avg1,avg2;

       Scanner kb = new Scanner(System.in);

       // Get the number of students from the user
       System.out.print("Enter # of students:");
       n = kb.nextInt();

       // Allocate the arrays
       names = new String[n];
       exam1Grades = new int[n];
       exam2Grades = new int[n];

       // Input the names and grades
       for (int i=0; i<=names.length-1; i++) {
          System.out.print("Enter name for student #" + (i+1) + ":");
          names[i] = kb.next();
          System.out.print("Enter exam #1 grade:");
          exam1Grades[i] = kb.nextInt();
          System.out.print("Enter exam #2 grade:");
          exam2Grades[i] = kb.nextInt();
       }

       // Add up all the grades (could have been done in the above loop)
       sum1 = 0;
       sum2 = 0;
       for (int i=0; i<=names.length-1; i++) {
          sum1 = sum1 + exam1Grades[i];
          sum2 = sum2 + exam2Grades[i];
       }

       // Calculate and output the averages
       avg1 = sum1/n;
       System.out.println();
       System.out.println("Exam #1 average: " + avg1);

       avg2 = sum2/n;
       System.out.println("Exam #2 average: " + avg2);
       System.out.println();

       // Compare each grade to the average
       for (int i=0; i<=names.length-1; i++) {
       if (exam1Grades[i] > avg1)
           System.out.println("Student " + names[i] + " is above average on exam 1");
           else if (exam1Grades[i] < avg1)
           System.out.println("Student " + names[i] + " is below average on exam 1");
           else
           System.out.println("Student " + names[i] + " is average on exam 1");

       if (exam2Grades[i] > avg2)
           System.out.println("Student " + names[i] + " is above average on exam 2");
           else if (exam2Grades[i] < avg2)
           System.out.println("Student " + names[i] + " is below average on exam 2");
           else
           System.out.println("Student " + names[i] + " is average on exam 2");

       }
    }
}

回答by Pablo Tricanico

like @Shobit said previously, use a BufferedWriter in conjunction with a FileWriter and with the methods write() and newLine() you can insert the lines you want to the file in stead of using Println.

就像@Shobit 之前所说的那样,将 BufferedWriter 与 FileWriter 结合使用,并且通过 write() 和 newLine() 方法,您可以将所需的行插入到文件中,而不是使用 Println。

BufferedWriter writer = new BufferedWriter(new FileWriter("path-of-file")); //you don't need to create a File object, FileWriter takes a string for the filepath as well
writer.write("Student number..."); 
writer.writeLine(); //for a new line in the file

and when you are done writing to the file,

当你完成写入文件时,

writer.close();

回答by deeban

    import java.nio.file.path;
    import java.nio.file.paths;
    class FileCopy {
    public static void main(String args[])
    {
    Path sour =Paths.get("Source path");
    Path dest =Paths.get("destination path"); // The new file name should be given  

    or else FileAlreadyExistsException occurs.                                            

    Files.copy(sour, dest);
    }
    }

回答by Pablo Tricanico

You can use the Scanner class the same way you use it to read the names of the file. All you have to do is define how you will structure your file. For example, separate your info with a special character i.e: "," and use that as a token to identify the different fields in your file for the name, grades, etc. (see the Patternand ScannerAPIs to use REGEX's for this)

您可以像使用 Scanner 类读取文件名一样使用它。您所要做的就是定义如何构建文件。例如,用特殊字符分隔您的信息,即:“,”,并使用它作为标记来标识文件中名称、等级等的不同字段(请参阅模式扫描仪API 以使用 REGEX)

You might want to create a Student class and map the needed fields to that class, add them to a List and iterate over that much easier.

您可能想要创建一个 Student 类并将所需的字段映射到该类,将它们添加到 List 并更容易地迭代。

As for writing to a text file, you are already doing it, check FileWriter to see how to add a new line and that will be it. Good Luck!

至于写入文本文件,你已经在做,检查 FileWriter 看看如何添加一个新行,就是这样。祝你好运!

回答by Shobit

You could use BufferedReader and BufferedWriter to read from/write to a file in Java. The BufferedReader constructor takes a FileReader object, whose constructor takes a File object. It looks something like this:

您可以使用 BufferedReader 和 BufferedWriter 在 Java 中读取/写入文件。BufferedReader 构造函数接受一个 FileReader 对象,其构造函数接受一个 File 对象。它看起来像这样:

BufferedReader br = new BufferedReader(new FileReader(new File("path-of-file")));

You can then read line-by-line from the file using the BufferedReader's readLine()(or any of the other methods depending on your use case).

然后,您可以使用 BufferedReader 的readLine()(或任何其他方法,具体取决于您的用例)从文件中逐行读取。

Analogically, there is also BufferedWriter and a FileWriter and a write()method for writing.

类似地,还有 BufferedWriter 和 FileWriter 以及一种write()写入方法。

Closing the reader and writer streams after reading/writing is always a good habit. You can use the closemethod on the streams to do the same.

在读/写之后关闭读者和作者流始终是一个好习惯。您可以close在流上使用该方法来执行相同的操作。

Hope that helps.

希望有帮助。