繁体   English   中英

读写Java中的.txt文件

[英]Reading and Writing to a .txt file in Java

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

我已编写并运行代码以使用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");

       }
    }
}

就像@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();

您可以使用与使用Scanner类一样的方式来读取文件名。 您所要做的就是定义如何构造文件。 例如,用特殊字符(即“,”)分隔您的信息,并将其用作标记以标识文件中名称,等级等的不同字段。(请参见PatternScanner API,为此使用REGEX)

您可能想要创建一个Student类,并将所需的字段映射到该类,将它们添加到List中,然后进行遍历。

至于写入文本文件,您已经在做,请检查FileWriter以了解如何添加新行。 祝好运!

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

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

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

以此类推,还有BufferedWriter和FileWriter以及用于write()方法。

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

希望能有所帮助。

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

暂无
暂无

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

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