Как удалить строчку из файла java
У меня есть файл BankAccount.txt как в нем имеются данные
Кредит:12500:1-
А что вы тут смотрите?:99999999:2-
Это надо закрыть:15428:3-
Люблю java:4850:4-
Долг Лехе:100050:5-
На отдых:2000:6-
После удаления 4 строки должно быть так
Кредит:12500:1-
А что вы тут смотрите?:99999999:2-
Это надо закрыть:15428:3-
Долг Лехе:100050:5-
На отдых:2000:6-
Общий код
import javax.swing.*;
import javax.swing.text.AttributeSet;
import javax.swing.text.BadLocationException;
import javax.swing.text.DocumentFilter;
import javax.swing.text.PlainDocument;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.*;
import java.util.Arrays;
import java.util.concurrent.ExecutionException;
import static java.lang.String.valueOf;
public class MainWindow extends JFrame implements ActionListener {
JPanel mainPanel, createPanel, closePanel, atmPanel;
JButton crBt, crBtBack, clBt, clBtBack, atmBt, atmBtBack, infoBt, crFinal, clFinal;
JLabel nameBank, nameSScore, nameMScore, unicId;
JTextField nameScore, moneyScore, idScore;
public MainWindow() {
//Имя окна
super("Нае(Банк)");
mainPanel = new JPanel();
mainPanel.setLayout(null);
createPanel = new JPanel();
createPanel.setLayout(null);
closePanel = new JPanel();
closePanel.setLayout(null);
atmPanel = new JPanel();
atmPanel.setLayout(null);
//Основная панель
crBt = new JButton("Создать счет");
crBt.setBounds(165, 150, 170, 25);
crBt.setActionCommand("createScore");
crBt.addActionListener(this);
clBt = new JButton("Закрыть счет");
clBt.setBounds(165, 200, 170, 25);
clBt.setActionCommand("closeScore");
clBt.addActionListener(this);
atmBt = new JButton("Банкомат");
atmBt.setBounds(165, 250, 170, 25);
atmBt.setActionCommand("atm");
atmBt.addActionListener(this);
infoBt = new JButton("Информация о счетах");
infoBt.setBounds(165, 300, 170, 25);
infoBt.setActionCommand("getInfo");
infoBt.addActionListener(this);
nameBank = new JLabel("Нае(БАНК)");
nameBank.setBounds(225, 100, 400, 30);
//Создащая счета панель
crBtBack = new JButton("Назад");
crBtBack.setBounds(165, 400, 170, 25);
crBtBack.setActionCommand("crBack");
crBtBack.addActionListener(this);
nameScore = new JTextField("", 10);
nameScore.setBounds(165, 150, 170, 25);
moneyScore = new JTextField("", 10);
moneyScore.setBounds(165, 200, 170, 25);
PlainDocument doc = (PlainDocument) moneyScore.getDocument();
doc.setDocumentFilter(new DigitFilter());
crFinal = new JButton("Создать");
crFinal.setBounds(165, 300, 170, 25);
crFinal.setActionCommand("crFinal");
crFinal.addActionListener(this);
nameSScore = new JLabel("Имя счета");
nameSScore.setBounds(225, 125, 400, 30);
nameMScore = new JLabel("Стартовый капитал");
nameMScore.setBounds(200, 175, 400, 30);
//Закрывающая панель счета
clBtBack = new JButton("Назад");
clBtBack.setBounds(165, 400, 170, 25);
clBtBack.setActionCommand("clBack");
clBtBack.addActionListener(this);
clFinal = new JButton("Закрыть счет");
clFinal.setBounds(165, 300, 170, 25);
clFinal.setActionCommand("clFinal");
clFinal.addActionListener(this);
idScore = new JTextField("", 10);
idScore.setBounds(165, 200, 170, 25);
PlainDocument doc1 = (PlainDocument) idScore.getDocument();
doc1.setDocumentFilter(new DigitFilter());
unicId = new JLabel("Уникальный идентификатор");
unicId.setBounds(165, 175, 400, 30);
//Панель банкомата
setSize(500, 500);
setDefaultCloseOperation(EXIT_ON_CLOSE);
setResizable(false);
getContentPane().add(mainPanel);
mainPanel.add(crBt);
mainPanel.add(clBt);
mainPanel.add(atmBt);
mainPanel.add(infoBt);
mainPanel.add(nameBank);
setVisible(true);
getContentPane().add(createPanel);
createPanel.add(crBtBack);
createPanel.add(nameScore);
createPanel.add(moneyScore);
createPanel.add(crFinal);
createPanel.add(nameSScore);
createPanel.add(nameMScore);
setVisible(true);
getContentPane().add(closePanel);
closePanel.add(clFinal);
closePanel.add(clBtBack);
closePanel.add(idScore);
closePanel.add(unicId);
setVisible(true);
getContentPane().add(atmPanel);
setVisible(true);
setVisible(true);
}
@Override
public void actionPerformed(ActionEvent e) {
if ("createScore".equals(e.getActionCommand())) {
createPanel.setVisible(true);
mainPanel.setVisible(false);
closePanel.setVisible(false);
atmPanel.setVisible(false);
}
if ("crBack".equals(e.getActionCommand())) {
createPanel.setVisible(false);
mainPanel.setVisible(true);
closePanel.setVisible(false);
atmPanel.setVisible(false);
}
if ("closeScore".equals(e.getActionCommand())) {
createPanel.setVisible(false);
mainPanel.setVisible(false);
closePanel.setVisible(true);
atmPanel.setVisible(false);
}
if ("clBack".equals(e.getActionCommand())) {
createPanel.setVisible(false);
mainPanel.setVisible(true);
closePanel.setVisible(false);
atmPanel.setVisible(false);
}
if ("crFinal".equals(e.getActionCommand())) {
try (FileWriter writer = new FileWriter("src/BankAccount.txt", true)) {
writer.write(nameScore.getText() + ":" + moneyScore.getText() + ":" + (strLeight() + 1) + "-\n");
writer.flush();
JOptionPane.showMessageDialog(MainWindow.this,
"Ваш счет " + nameScore.getText() + " создан с балансом " + moneyScore.getText() + "\nЕго уникальный идентификатор " + strLeight() + "\nСпасибо что используете наш банк", "Создание счета"
, JOptionPane.INFORMATION_MESSAGE);
nameScore.setText("");
moneyScore.setText("0");
} catch (IOException ex) {
System.out.println(ex.getMessage());
}
}
if ("getInfo".equals(e.getActionCommand())) {
JOptionPane.showMessageDialog(MainWindow.this,
"Тут будут счета",
"Информация о счетах\n"
, JOptionPane.INFORMATION_MESSAGE);
}
if ("clFinal".equals(e.getActionCommand())) {
try (FileWriter writer = new FileWriter("src/BankAccount.txt", true)) {
System.out.println(idScore.getText());
} catch (IOException ex) {
System.out.println(ex.getMessage());
}
}
}
public static void main(String[] args) {
new MainWindow();
}
public static int strLeight() {
try {
File myFile = new File("src/BankAccount.txt");
FileReader fileReader = new FileReader(myFile);
LineNumberReader lineNumberReader = new LineNumberReader(fileReader);
int lineNumber = 0;
while (lineNumberReader.readLine() != null) {
lineNumber++;
}
lineNumberReader.close();
return lineNumber;
} catch (IOException e) {
e.printStackTrace();
}
return 0;
}
static class DigitFilter extends DocumentFilter {
private static final String DIGITS = "\\d+";
@Override
public void insertString(FilterBypass fb, int offset, String string, AttributeSet attr) throws BadLocationException {
if (string.matches(DIGITS)) {
super.insertString(fb, offset, string, attr);
}
}
@Override
public void replace(FilterBypass fb, int offset, int length, String string, AttributeSet attrs) throws BadLocationException {
if (string.matches(DIGITS)) {
super.replace(fb, offset, length, string, attrs);
}
}
}
}
Желательно что бы работал в этом куске кода
if ("clFinal".equals(e.getActionCommand())) {
try (FileWriter writer = new FileWriter("src/BankAccount.txt", true)) {
// Вот здесь
} catch (IOException ex) {
System.out.println(ex.getMessage());
}
}
Ответы (1 шт):
Если вы пытаетесь использовать текстовый файл для хранения ваших данных, то это очень плохая идея. Лучше сделайте класс-сервис, эмулирующий работу с базой данных, который для начала будет использовать коллекцию для хранения данных. Если хотите, то можете добавить сохранение этой коллекции на диск (хотя в этом случае лучше подключит бд). Что касается сохранения в файл, реализовать это достаточно несложно, но повторюсь : не стоит это использовать как БД. Посему реализация такова: создаем класс - модель, хранящую инфу о идентификаторе, сумме и описании счета. Создаем класс - сервис, вмещающий логику работы с нашими данными (объектами класса-модели), в т.ч. эмулирующий БД. Класс-сервис будет иметь методы как для работы с нашей коллекцией (в дальнейшем БД), так и методы, создания тектового файла, его чтения и записи. Ну и правим вьюху. Я не делаю реализацию сервиса через интерфейс(хотя именно так и нужно делать), это останется на вашей совести, ровно как и подключение реальной БД.
import java.awt.Component;
import java.awt.event.ActionEvent;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.Collection;
import java.util.Map;
import java.util.Optional;
import java.util.TreeMap;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.text.AttributeSet;
import javax.swing.text.BadLocationException;
import javax.swing.text.DocumentFilter;
import javax.swing.text.JTextComponent;
import javax.swing.text.PlainDocument;
import static java.nio.file.StandardOpenOption.*;
import java.util.function.Consumer;
public class MainWindow extends JFrame {
private static final long serialVersionUID = 3025189256705831368L;
private final static String FILE_NAME = "BankAccount.txt";
private final AccountService service;
public MainWindow() {
//Имя окна
super("Нае(Банк)");
this.service = new AccountService();
JPanel mainPanel = new JPanel();
mainPanel.setLayout(null);
JPanel createPanel = new JPanel();
createPanel.setLayout(null);
JPanel closePanel = new JPanel();
closePanel.setLayout(null);
JPanel atmPanel = new JPanel();
atmPanel.setLayout(null);
JLabel nameBank = new JLabel("Нае(БАНК)");
nameBank.setBounds(225, 100, 400, 30);
JLabel nameSScore = new JLabel("Имя счета");
nameSScore.setBounds(225, 125, 400, 30);
JLabel nameMScore = new JLabel("Стартовый капитал");
nameMScore.setBounds(200, 175, 400, 30);
JLabel unicId = new JLabel("Уникальный идентификатор");
unicId.setBounds(165, 175, 400, 30);
JTextField nameScore = new JTextField("", 10);
nameScore.setBounds(165, 150, 170, 25);
JTextField moneyScore = new JTextField("", 10);
moneyScore.setBounds(165, 200, 170, 25);
addDigitFilter(moneyScore);
JTextField idScore = new JTextField("", 10);
idScore.setBounds(165, 200, 170, 25);
addDigitFilter(idScore);
JButton crBt = createButton("Создать счет", 150, e -> setVisible(createPanel, mainPanel, closePanel, atmPanel));
JButton clBt = createButton("Закрыть счет", 200, e -> setVisible(closePanel, createPanel, mainPanel, atmPanel));
JButton atmBt = createButton("Банкомат", 250, e -> setVisible(atmPanel, createPanel, mainPanel, closePanel));
JButton infoBt = createButton("Информация о счетах", 300, e -> showMessage("Информация о счетах\n", service.accountToString(service.findAll())));
JButton crBtBack = createButton("Назад", 400, e -> setVisible(mainPanel, createPanel, closePanel, atmPanel));
JButton clBtBack = createButton("Назад", 400, e -> setVisible(mainPanel, createPanel, closePanel, atmPanel));
JButton crFinal = createButton("Создать", 300, e -> {
try {
Account account = service.save(new Account(Long.valueOf(moneyScore.getText().trim()), nameScore.getText().trim()));
service.writeFile(FILE_NAME);
showMessage("Создание счета",
"Ваш счет " + account.getComment() +
" создан с балансом " + account.getAmount() +
"\nЕго уникальный идентификатор " + account.getId() +
"\nСпасибо что используете наш банк");
nameScore.setText("");
moneyScore.setText("0");
} catch (IOException | RuntimeException ex) {
showMessage("Ошибка", ex.getMessage());
}
});
JButton clFinal = createButton("Закрыть счет", 300, e -> {
try {
service.deleteById(Long.valueOf(idScore.getText()));
service.writeFile(FILE_NAME);
showMessage("Закрытие счета", "Счет №" + idScore.getText() + " закрыт");
idScore.setText("0");
} catch (IOException | RuntimeException ex) {
showMessage("Ошибка", ex.getMessage());
}
});
setSize(500, 500);
setDefaultCloseOperation(EXIT_ON_CLOSE);
setResizable(false);
this.addPanel(mainPanel, crBt, clBt, atmBt, infoBt, nameBank)
.addPanel(createPanel, crBtBack, nameScore, moneyScore, crFinal, nameSScore, nameMScore)
.addPanel(closePanel, clFinal, clBtBack, idScore, unicId)
.addPanel(atmPanel, crBtBack);// добавляем в аргументах нужные компоненты
setVisible(true);
}
private JButton createButton(String label, int y, Consumer<ActionEvent> consumer){
final JButton button = new JButton(label);
button.setBounds(165, y, 170, 25);
button.addActionListener(e -> consumer.accept(e));
return button;
}
private MainWindow addPanel(JPanel panel, Component ... components){
getContentPane().add(panel);
for (Component component : components) panel.add(component);
setVisible(true);
return this;
}
private void setVisible(Component visibleComponent, Component... invisibleComponents) {
for (Component component : invisibleComponents) component.setVisible(false);
visibleComponent.setVisible(true);
}
private void showMessage(String title, String message) {
JOptionPane.showMessageDialog(MainWindow.this,
message, title,
JOptionPane.INFORMATION_MESSAGE);
}
private void addDigitFilter(JTextComponent component){
((PlainDocument) component.getDocument()).setDocumentFilter(new DigitFilter());
}
public static void main(String[] args) {
java.awt.EventQueue.invokeLater(() -> new MainWindow());
}
static class DigitFilter extends DocumentFilter {
private static final String DIGITS = "\\d+";
@Override
public void insertString(FilterBypass fb, int offset, String string, AttributeSet attr) throws BadLocationException {
if (string.matches(DIGITS)) super.insertString(fb, offset, string, attr);
}
@Override
public void replace(FilterBypass fb, int offset, int length, String string, AttributeSet attrs) throws BadLocationException {
if (string.matches(DIGITS)) super.replace(fb, offset, length, string, attrs);
}
}
}
class AccountService {
private final Map<Long, Account> accounts = new TreeMap<>();
private Long ID_COUNTER = 0L;
public void deleteById(Long id){
accounts.remove(id);
}
public Optional<Account> findById(Long id){
return accounts.containsKey(id) ? Optional.of(accounts.get(id)) : Optional.empty();
}
public Collection<Account> findAll (){
return accounts.values();
}
public Account save(Account account){
account.setId(++ID_COUNTER);
accounts.put(ID_COUNTER, account);
return account;
}
public long count(){
return accounts.size();
}
public String readFile(String fileName) throws IOException {
try (Stream<String> stream = Files.lines(Paths.get(fileName))) {
return stream.collect(Collectors.joining("\r\n"));
}
}
public void writeFile(String fileName) throws IOException {
Files.write(Paths.get(fileName), accountToString(accounts.values()).getBytes(), CREATE, WRITE);
}
public String accountToString(Collection<Account> accounts) {
return accounts.stream()
.map(Account::toString)
.collect(Collectors.joining("\r\n"));
}
}
class Account {
private Long id;
private Long amount;
private String comment;
public Account(Long amount, String comment) {
this.amount = amount;
this.comment = comment;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public Long getAmount() {
return amount;
}
public void setAmount(Long amount) {
this.amount = amount;
}
public String getComment() {
return comment;
}
public void setComment(String comment) {
this.comment = comment;
}
@Override
public String toString() {
return comment + ":" + amount + ":" + id;
}
}