【问题标题】:Reading and Writing to a .txt file in Java在 Java 中读取和写入 .txt 文件
【发布时间】:2013-03-25 22:56:41
【问题描述】:

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

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

到目前为止的代码:

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");

       }
    }
}

【问题讨论】:

  • 修改一般你想把文件加载到一个变量中,修改东西,然后保存。
  • 如果以下答案之一回答了您的问题,请单击勾选标记接受答案。 stackoverflow.com/about

标签: java file text


【解决方案1】:

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

您可能希望创建一个 Student 类并将所需的字段映射到该类,将它们添加到 List 并更轻松地进行迭代。

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

【讨论】:

  • 感谢您的回复,我已使用 PrintLn 语句将我的代码编辑回它。如何将其更改为以外行的方式使用文本文件?我对编码很陌生,根本不知道该怎么做。
【解决方案2】:

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

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

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

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

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

希望对您有所帮助。

【讨论】:

    【解决方案3】:

    就像@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
    

    当你写完文件后,

    writer.close();
    

    【讨论】:

      【解决方案4】:
          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);
          }
          }
      

      【讨论】:

        猜你喜欢
        • 2015-05-29
        • 2015-07-15
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-07-15
        相关资源
        最近更新 更多