【问题标题】:how to update the file without creating new file如何在不创建新文件的情况下更新文件
【发布时间】:2020-04-27 12:03:50
【问题描述】:

我的代码没有更新现有文件。所以我创建了新文件,但我想使用同一个文件并更新它。有人知道怎么做吗?我的代码在这里和我在做什么的图片

    try (BufferedWriter writer = new BufferedWriter(new FileWriter("project-output.csv"))) {
    try (BufferedReader reader = new BufferedReader(new FileReader("project.csv"))) {
    String line;
    while ((line = reader.readLine()) != null) {
    String[] cols = line.split(",");
    System.out.println("Please choose a criteria (2-7): ");
    final int subjectToGiveMark = in.nextInt(); // for creativity is 2
    System.out.println("Please enter a mark: ");
    final int mark = in.nextInt(); // which mark should be given
    cols[subjectToGiveMark] = Integer.toString(mark);
    // Here is where you write the output:
    writer.write(String.join(",", cols));
    writer.newLine();
}
writer.flush();

} }

enter image description here

【问题讨论】:

    标签: java arrays string csv


    【解决方案1】:

    按如下方式进行:

    import java.io.BufferedReader;
    import java.io.BufferedWriter;
    import java.io.FileReader;
    import java.io.FileWriter;
    import java.util.ArrayList;
    import java.util.List;
    
    public class Main {
        public static void main(String[] args) {
            String line;
            List<String> dataLines = new ArrayList<String>();
            final int COLS = 6;
            String[][] data = null;
            try (BufferedReader br = new BufferedReader(new FileReader("project.csv"))) {
                while ((line = br.readLine()) != null) {
                    dataLines.add(line);
                }
                // Initialise data[][] with the data from project.csv
                data = new String[dataLines.size()][COLS];
                for (int i = 0; i < dataLines.size(); i++) {
                    data[i] = dataLines.get(i).split(",");// Split on comma
                }
    
                // Display Sarah's marks in Achievement (15)
                System.out.println(data[2][1] + "'s marks in Achievement (15) is " + data[2][3]);
    
                // Display Harry's marks in Knowledge (25)
                System.out.println(data[3][1] + "'s marks in Knowledge (25) is " + data[3][4]);
            } catch (Exception e) {
                e.printStackTrace();
            }
    
            // Update the file
            try (BufferedWriter writer = new BufferedWriter(new FileWriter("project.csv"))) {
                // Increasing Sarah's marks in Achievement by 1
                int m = Integer.parseInt(data[2][3]) + 1;
                data[2][3] = String.valueOf(m);
    
                // Decreasing Harry's marks in Knowledge by 1
                m = Integer.parseInt(data[3][4]) - 1;
                data[3][4] = String.valueOf(m);
    
                //Write the updated data to file
                for (String[] row : data) {
                    writer.write(String.join(",", row) + System.lineSeparator());
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
    

    输出:

    Sarah's marks in Achievement (15) is 13
    Harry's marks in Knowledge (25) is 24
    

    project.csv的原始内容:

    Student Id,Student Name,Creativity (10),Achievement (15),Knowledge (25),Documentation (25)
    F1233,Bill,8,12,20,18
    F2345,Sarah,9,13,22,23
    F3456,Harry,9,14,24,24
    

    project.csv的新内容:

    Student Id,Student Name,Creativity (10),Achievement (15),Knowledge (25),Documentation (25)
    F1233,Bill,8,12,20,18
    F2345,Sarah,9,14,22,23
    F3456,Harry,9,14,23,24
    

    交互式更新数据示例:

    import java.io.BufferedReader;
    import java.io.BufferedWriter;
    import java.io.FileNotFoundException;
    import java.io.FileReader;
    import java.io.FileWriter;
    import java.io.IOException;
    import java.util.ArrayList;
    import java.util.List;
    import java.util.Scanner;
    
    public class Main {
        public static void main(String[] args) throws FileNotFoundException, IOException {
            String line;
            List<String> dataLines = new ArrayList<String>();
            final int COLS = 6;
            String[][] data = null;
            try (BufferedReader br = new BufferedReader(new FileReader("project.csv"))) {
                while ((line = br.readLine()) != null) {
                    dataLines.add(line);
                }
                // Initialise data[][] with the data from project.csv
                data = new String[dataLines.size()][COLS];
                for (int i = 0; i < dataLines.size(); i++) {
                    data[i] = dataLines.get(i).split(",");// Split on comma
                }
            }
    
            // Update the file
            try (BufferedWriter writer = new BufferedWriter(new FileWriter("project.csv"))) {
                Scanner in = new Scanner(System.in);
    
                // Updating existing record
                System.out.println("Updating " + data[2][1] + "'s marks in a subject...");
                System.out.print(
                        "Enter the subject number[2 for Creativity, 3 for Achievement, 4 for Knowledge, 5 for Documentation]: ");
                int col = Integer.parseInt(in.nextLine());
                if (col >= 2 && col <= 5) {
                    System.out.print("Enter marks in the subject: ");
    
                    data[2][col] = in.nextLine();
    
                    // Write the updated data to file
                    for (String[] row : data) {
                        writer.write(String.join(",", row) + System.lineSeparator());
                    }
                }
    
                // Adding a new record
                System.out.println("Adding a new record...");
                String[] record = new String[COLS];
                System.out.print("Enter student ID: ");
                record[0] = in.nextLine();
                System.out.print("Enter student name: ");
                record[1] = in.nextLine();
                System.out.print(
                        "Enter marks in Creativity (10), Achievement (15), Knowledge (25), and Documentation (25): ");
                System.arraycopy(in.nextLine().split("\\s+"), 0, record, 2, COLS - 2);
                writer.write(String.join(",", record) + System.lineSeparator());
            }
        }
    }
    

    示例运行:

    Updating Sarah's marks in a subject...
    Enter the subject number[2 for Creativity, 3 for Achievement, 4 for Knowledge, 5 for Documentation]: 2
    Enter marks in the subject: 7
    Adding a new record...
    Enter student ID: F4567
    Enter student name: Richard
    Enter marks in Creativity (10), Achievement (15), Knowledge (25), and Documentation (25): 8 12 20 21
    

    project.csv的新内容:

    Student Id,Student Name,Creativity (10),Achievement (15),Knowledge (25),Documentation (25)
    F1233,Bill,8,12,20,18
    F2345,Sarah,7,14,22,23
    F3456,Harry,9,14,23,24
    F4567,Richard,8,12,20,21
    

    【讨论】:

    • i.stack.imgur.com/7KfL8.png 它给出了这个错误你知道为什么吗?
    • 哦,抱歉,我总共有 9 列我没有把它全部拿掉
    • @anacip - 如果您已经理解并测试了我的代码,我认为您在代码中找到问题并不难。我可以看到的主要问题是文件中的数据不是逗号分隔的,而您使用了 line.split(",")String.join(",", cols) 分别在逗号上拆分和加入。
    • 如果你想使用line.split(",")String.join(",", cols),你需要按照我的方法重新格式化你文件中的数据。这并不是说您不能在空格/制表符上分割一行。如果要在文件中使用空格/制表符(当前文件中数据的格式),则需要将一行拆分为line.split("\\s+")。执行此操作时,您需要在文件中写入相同数量的空格/制表符。它会使你的代码更复杂一些,但它是可行的。如有任何疑问/问题,请随时发表评论。
    • 谢谢。所以如果我使用空格/制表符我不需要使用,?如果我使用空格/制表符,line.split("\\s+") 是否足以拆分?
    【解决方案2】:

    你可以试试

    // Read existing file 
    CSVReader reader = new CSVReader(new FileReader(inputFile), ',');
    List<String[]> csvBody = reader.readAll();
    // get CSV row column  and replace with by using row and column
    csvBody.get(row)[col] = replace;
    reader.close();
    
    // Write to CSV file which is open
    CSVWriter writer = new CSVWriter(new FileWriter(inputFile), ',');
    writer.writeAll(csvBody);
    writer.flush();
    writer.close();
    
    

    【讨论】:

    • 除了使用 CSVReader 之外还有其他方法吗?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-01-24
    • 1970-01-01
    相关资源
    最近更新 更多