как обновить файл без создания нового файла - PullRequest
0 голосов
/ 27 апреля 2020

Мой код не обновляет существующий файл. Поэтому я создаю новый файл, но я хочу сделать с тем же файлом и обновить его. Кто-нибудь знает, как это сделать? мой код здесь и изображение того, что я делаю

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

}}

введите описание изображения здесь

Ответы [ 2 ]

0 голосов
/ 27 апреля 2020

Сделайте это следующим образом:

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
0 голосов
/ 27 апреля 2020

можете попробовать

// 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();

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...