简体   繁体   English

如何在Java中从.txt文件提取信息?

[英]How do I pull information form a .txt file in Java?

I currently have some code that can take console input, but I need to make it recognize a list of names and test scores. 我目前有一些可以接受控制台输入的代码,但是我需要使其识别名称和测试分数的列表。 Code that I currently have: 我目前拥有的代码:

import java.io.*;
import utils.io.*;

class student
{
   String name;
   double sResult[];
   int result;
   double sum;

   void getdata()
   {
      System.out.println("Enter name:");
      Name = (string) system.in.read();
      int index=0;

      for (int counter=1; counter<=5; counter++)
      {
         System.out.println("Enter result for subject"+counter+":");
         sResult[count] = (double) system.in.read();
      }
   }

   public static void CalculateAverage()
   {
      sum = 0;
      for (int i=1;i<=5;i++)
      {
         sum += sResult[i];
      }
      return (int) Math.round(sum/(values.length-1));
   }

   Public static char calculateGrade()
   {
      result=sum;
      if (result>=0 && result <=59)
      {
         return ('F');
      }
      else
      if (result >=60 && result<=69)
      {
         return ('E');
      }
      else
      if (result>=0 && result<79)
      {
         return ('D');
      }
      else
      if (result >=70 && result<=79)
      {
         return ('C');
      }
      else
      if (result>=80 && result<=89)
      {
         return ('B');
      }
      else
      if (result>=90 && result<=100)
      {
         return ('A');
      }
   }
}

and class test 和课堂测试

public class test
{
   public static void main(String[] args)
{
   Student std;
   do
   {
      std=new Student();
      std.getdata();
      System.out.println("Student Name:"+std.Name);
      System.out.println("Average for"+std.Name+" "+"is:"+std.average());
      System.out.println("Grade for"+std.Name+" "+"is:"+std.gradecal());
      System.out.println("Want to continue (1-Yes,2-No");
   }
   while(System.in.read()==1);
}

The text document format is name score1 score2 score3 score4 score5 文本文档格式为名称score1 score2 score3 score4 score5

I only need help figuring out how to import the values, and then I can probably figure out how to rewrite the .txt using PrintWriter. 我只需要帮助弄清楚如何导入值,然后就可以弄清楚如何使用PrintWriter重写.txt。

Thanks in advance for any help! 在此先感谢您的帮助!

Firstly, you should not have variable names starting with a capital, namely: 首先,您不应使用以大写字母开头的变量名称,即:

string Name;

Only class names should start with a capital. 仅类别名称应以大写字母开头。

Also, I'm not even sure if your code compiles. 另外,我什至不确定您的代码是否可以编译。 Everywhere you have system.out.println should be System.out.println . 到处都有system.out.println应该是System.out.println Notice that System is a class, so the first letter is a capital 请注意,System是一个类,因此第一个字母是大写

To read data, you can use BufferedReader and to write, you can use BufferedWriter . 要读取数据,可以使用BufferedReader进行写入,可以使用BufferedWriter Usage: 用法:

BufferedReader in = new BufferedReader(new FileReader("FileName.txt"));
BufferedWriter out = new BufferedWriter(new FileWriter("OutputFileName.txt"));

in.readLine(); //This reads a single line from the text file
out.write("Your Output Text");
in.close(); // Closes the file input stream
out.close(); // Closes the file output stream

Since you are reading in the format: 由于您正在阅读以下格式:

name score1 score2 score3 score4 score5 名称分数1分数2分数3分数4分数5

you can use the some String functions to get each field. 您可以使用一些String函数来获取每个字段。

String inputLine = in.readLine();
String [] fields = inputLine.split(" "); // Splits at the space
System.out.println(fields[0]); //prints out name
System.out.println(fields[1]); //print out score1
...

Here's how you do it with Scanner . 这是使用Scanner

Scanner inputFile = new Scanner(new File("inputfile.txt"));
while(inputFile.hasNext()){ //if there is still something to read
     String name = inputFile.next();
     int score1 = inputFile.nextInt();    
     ....
     int score5 = inputFile.nextInt();
     //Do something here with the scores
     inputFile.next(); //Read the new line character and prepare for the next iteration 
}

For writing back to file, you can check Davy's answer and use a Buffered Writer. 要写回文件,您可以检查Davy的答案并使用Buffered Writer。 Note that the write() method works just like System.out.println() but you need to print \\n on your own to go to the new line. 请注意, write()方法的工作方式与System.out.println()但是您需要自己打印\\n才能转到新行。

public static void main(String... args) throws IOException {
    Scanner s = new Scanner(new BufferedReader(new FileReader("textfile.txt")));
    while(s.hasNext()){
        Student student = new Student(s.next(), s.nextDouble(), s.nextDouble(),
                                      s.nextDouble(), s.nextDouble(), s.nextDouble() ));
        // Do something with student
        s.next() // consume endline
    }
}

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

相关问题 如何解压缩具有多个txt文件的zip文件并将其转换为新的txt文件,而不会覆盖Java中文件中的信息 - How do I unzip a zip file with multiple txt file and turn it into a new txt file with out overwritten the information in the file in java 如何从Java中的txt文件提取以下信息 - How can I extract the following information from a txt file in java 如何从 java 中的 .txt 文件中获取特定信息? - How can I get specific information out of a .txt file in java? 如何从txt文件读取Java中的2个特定列? - How do I read 2 particular columns in Java from a txt file? 如何计算Java中txt文件中某个特定单词的出现? - How do I count an occurence of a specific word in a txt file in Java? Java:如何导出使用.txt文件的程序? - Java: How do I export a program which uses a .txt file? 如何在 Java 中将 JTextField 输入保存到 .txt 文件? - How Do I Save JTextField Inputs to a .txt file in Java? 如何将数据从txt文件拉入HTML表Java / JSP - How to pull data from a txt file into a HTML table Java/JSP 如何从 Java 中的 txt 文件中读取 2 个特定列? - How do I read 2 particular columns from a txt file in Java? 当我必须使用文件阅读器Java时,如何从txt文件填充数组? - How do i populate an array from a txt file when i have to use file reader Java??
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM