HashMap混乱。读/写文件。 Java的

时间:2015-03-25 19:49:30

标签: java file hashmap filewriter

到目前为止

代码:

public class test1 {                                                                                                           

public static void main(String[] args) throws IOException {                                                                
    //declare reader and writer                                                                                            
    BufferedReader reader = null;                                                                                          
    PrintWriter writer = null;                                                                                             

    //hash maps to store the data                                                                                          
    HashMap<String, String> names = new HashMap<String, String>();                                                         


    //read the first file and store the data                                                                               
    reader = new BufferedReader(new InputStreamReader(new FileInputStream(new File("IRStudents.txt"))));                   
    String line;                                                                                                           
    String[] arg;                                                                                                          

    while ((line = reader.readLine()) != null) {                                                                           
        if (!line.startsWith("-")) {                                                                                       
            arg = line.split(" ");                                                                                         


            names.put(arg[0], arg[1]);                                                                                     


        }                                                                                                                  
    }                                                                                                                      
    reader.close();                                                                                                        

//read the second file, merge the data and output the data to the out file
writer = new PrintWriter(new FileOutputStream(new File("File_2.txt")));
reader = new BufferedReader(new InputStreamReader(new FileInputStream(new File("Marks.txt"))));
while((line = reader.readLine()) != null){
    arg = line.split(" ");
    writer.println(arg[0] + " " + names.get(arg[0]));
    writer.println("Marks: " + arg[1]);
    writer.println("- - - - - -");
}                                                                          


        writer.flush();                                                                                                    
        writer.close();                                                                                                    
        reader.close();                                                                                                    
    }                                                                                                                      
} 

因此文本文件中的输出如下所示:

 25220 Fiona
 Marks: 68.3
 - - - - - -
 25212 Greg
 Marks: 70.5
 - - - - - -       

我有另一个文本文件,其中包含另一组标记,其布局与第一个标记文件相同。

现在我想为数据集添加一组新标记所以它应该如下所示:

 25220 Fiona
 Marks: 68.3  Marks2: 21.2
 - - - - - -
 25212 Greg
 Marks: 70.5  Marks2: 23.43
 - - - - - -         

那我该怎么做才能添加?我假设我必须为新的文本文档添加一个新的Hashmap?但是,当我尝试所有这一切时,它永远不会完全奏效。

IR学生:

25987 Alan
25954 Betty
25654 Chris
25622 David                                                                                                      

4 个答案:

答案 0 :(得分:1)

我认为你做了太多的字符串操作。如果你有更多的分数&#39;要以类似的方式处理文件,String操作可能会增加,这可能会使您的代码可读性降低,并且可能为错误提供更多空间。我认为以下是一种更好的方法。

您可以使用以下结构创建MarksRecord类。

public class MarksRecord {
   private String subject; // or whatever this variable name should be.
                           // in your case it should hold value marks1.
   private double marks;

}

同样,你可以创建一个不可变的Student /类似的类,如下所示。这可以是一个值类,其中包含基于您在每个文件中读取的第一个数字的equals和hashCode方法。我猜它是卷号或类似的,可以用一种独特的方式识别学生。

public final class Student {
    private final String rollNumber;
    private final String name;

    // equals, hashCode, and other methods.
}

然后在你的主要方法中你可以有一个

Map<Student, ArrayList<MarksRecord>>

。或者你也可以使用

Map<String, ArrayList<MarksRecord>>

其中第一个String是学生记录的卷号。

这样每次有新的标记文件时,您的数据结构都可以容纳它。

答案 1 :(得分:1)

您也可以执行以下操作。

package toBeDeleted;

import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

public class MarksProcessor {


    private final Map<String, Record> map = new HashMap<>();

    public static void main(String[] args) {
        String fileName = "file1.txt"; // change it to your specific file.
        MarksProcessor marksProcessor = new MarksProcessor();
        marksProcessor.processFile(fileName, 0);
        fileName = "file2.txt";
        marksProcessor.processFile(fileName, 1);
        marksProcessor.writeData();

    }

    private void processFile(String fileName, int marksIndex) {
        try(/*specify your reader resources here*/) {
            // read the first record and get rollNumber, name and marks.
            String roll = "valueYouGot";
            double value = 0.0; // the value you read.
            Record record = map.get(roll);
            // if record is null, you need to create one
            // and put it into the map.
            //record.updateMarks(marksndex, value);
        }
    }

    private void writeData() {

        // if this needs to be written to a file/stream, create a writer.
        for (Map.Entry<String, Record> entry : map.entrySet()) {
            String roll = entry.getKey();
            Record record = entry.getValue();
            if (record != null) {
                String name = record.getName();
                double marks1 = record.getMarks(0);
                double marks2 = record.getMarks(1);
                // Now you have all the values. Print them 
                // however you like. Wherever you like.
            }
        }
    }

    static class Record {
        private String name;
        private double[] marks = new double[2];


        Record(String name) {
            this.name = name;
        }

        public String getName() {
            return name;
        }

        public double getMarks(int index) {
            if (index < 0 || index > 1)
                throw new IllegalArgumentException("index should be 0 or 1 but"
                        + " the supplied index was " + index);
            return marks[index];
        }
        public void updateMarks(int index, double value ) {
            if (index < 0 || index > 1)
                throw new IllegalArgumentException("index should be 0 or 1 but"
                        + " the supplied index was " + index);
            marks[index] = value;
        }


        @Override
        public String toString() {
            return "the way you want to type your output";
        }

    }


}

答案 2 :(得分:0)

添加新标记时,使用此标记将它们添加到现有标记中:

String key = arg[0];
String secondMarks = arg[1];

String theMarks = names.get(key);
theMarks = theMarks + " Marks2: " + secondMarks;
names.put(key, theMarks);

答案 3 :(得分:0)

我想我理解你的问题,请告诉我这是不正确的。

要求是让所有人在自己的线路上接受的标记......

System.out流中的两个打印功能。

print and println

arg = line.split(" ");
writer.println(arg[0] + " " + names.get(arg[0]));

writer.print("Marks: " + arg[1]);
for(int i = 2; i < args.length; i++){
    writer.println(" Marks" + i + ": " + arg[i]);
}

writer.println("\n- - - - - -");