質問

私がしようとしていることは私が作った予約を削除することです TXTファイルでは予約がこのようになります。

08:00
Niel Butaye
1
.

予約を削除する必要があるコードは次のとおりです。

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.File;
import java.io.FileWriter;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.PrintWriter;

public class ReservatieVerwijderen {
    static String naamklant="";
    public ReservatieVerwijderen() {}

  public void removeLineFromFile(String file, String lineToRemove) {

    try {

      File inFile = new File(file);

      if (!inFile.isFile()) {
        System.out.println("Parameter is not an existing file");
        return;
      }

      //Maak een nieuw bestand dat later het originele bestand wordt
      File tempFile = new File(inFile.getAbsolutePath() + ".tmp");

      BufferedReader br = new BufferedReader(new FileReader(file));
      PrintWriter pw = new PrintWriter(new FileWriter(tempFile));

      String line = null;

      //Lees het originele bestand en schrijf naar het tijdelijke bestand 
      //Als de lijn == de lijn die we zoeken schrijven we dit niet over
      while ((line = br.readLine()) != null) {

        if (!line.trim().equals(lineToRemove)) {

          pw.println(line);
          pw.flush();
        }
      }
      pw.close();
      br.close();

      //Verwijder het originele bestand
      if (!inFile.delete()) {
        System.out.println("Could not delete file");
        return;
      } 

      //Hernoem het tijdelijke bestand naar het originele
      if (!tempFile.renameTo(inFile))
        System.out.println("Could not rename file");

    }
    catch (FileNotFoundException ex) {
      ex.printStackTrace();
    }
    catch (IOException ex) {
      ex.printStackTrace();
    }
  }

  public static void main(String[] args) {
    ReservatieVerwijderen util = new ReservatieVerwijderen();
    SimpleInOutDialog  input = new SimpleInOutDialog("Reserveringen");
    naamklant = input.readString("Geef de volledige naam in");
    util.removeLineFromFile("L:\\Documents/Informatica/6de jaar/GIP/Reserveringen.txt", naamklant);
  }
}
.

予約メーカーの名前のみを削除し、1時間(08:00)と予約の種類(1)を削除する必要があります。

public class SimpleInOutDialog {

    private String titel;

    /**
     * Constructor van een SimpleInOutDialog.
     *
     * @param titel een String met de titel van het venstertje.
     */
    public SimpleInOutDialog(String titel) {
        this.titel = titel;
    }
    /**
     * Tonen van een tekst in een dialoogvenstertje. 
     * @param message een String met een te tonen berichtje.
     * @param output een String met de te tonen tekst.
     */
    /**
    *  
    * @param 
    */


    public void showString(String message, String output) {
        JOptionPane.showMessageDialog(
            null,
            message + "\n\n" + output + "\n\n",
            titel,
            JOptionPane.PLAIN_MESSAGE);

    }

    /**
    * Tonen van een geheel getal in een dialoogvenstertje.  
    * @param message een String met een te tonen berichtje.
    * @param een int met het te tonen getal.
    */
    public void showInteger(String message, int getal) {
        JOptionPane.showMessageDialog(
            null,
            message + "\n\n" + Integer.toString(getal) + "\n\n",
            titel,
            JOptionPane.PLAIN_MESSAGE);

    }

    /**
    * Tonen van een geheel getal in een dialoogvenstertje.
    * @param message een String met een te tonen berichtje.  
    * @param een double met het te tonen getal.
    */
    public void showDouble(String message, double getal) {
        JOptionPane.showMessageDialog(
            null,
            message + "\n\n" + Double.toString(getal) + "\n\n",
            titel,
            JOptionPane.PLAIN_MESSAGE);
    }

    /**
     * Inlezen van een String.
     * @param message een String met de tekst die in het dialoogvenster
     * moet getoond worden.
     * @return de ingelezen String.  Indien het venster zonder
     * invoer wordt afgesloten is de String null.
     */
    public String readString(String message) {
        Object[] possibilities = null;
        String s = null;
        s =
            (String) JOptionPane.showInputDialog(
                null,
                message,
                this.titel,
                JOptionPane.PLAIN_MESSAGE,
                null,
                possibilities,
                "");

        if ((s == null) || (s.length() == 0)) {
            s = null;
        }
        return s;
    }

    /**
     * Inlezen van een geheel getal.
     * @param message een String met de tekst die in het dialoogvenster
     * moet getoond worden.
     * @return het ingelezen geheel getal (een int).  Indien het venster zonder
     * correcte invoer wordt afgesloten is het getal 0 (nul).
     */
    public int readInteger(String message) {
        boolean isAnInteger = false;
        String tekst = null;
        int gelezen = 0;
        while (!isAnInteger) {
            tekst = readString(message);
            if (tekst != null) {
                try {
                    gelezen = Integer.parseInt(tekst);
                    isAnInteger = true;
                } catch (NumberFormatException nfe) {
                    isAnInteger = false;
                }
            } else {
                isAnInteger = true;
                gelezen = 0;
            }
        }
        return gelezen;
    }

    /**
     * Inlezen van een kommagetal.
     * @param message een String met de tekst die in het dialoogvenster
     * moet getoond worden.
     * @return het ingelezen getal (een double).  Indien het venster zonder
     * correcte invoer wordt afgesloten is het getal 0.0 (nul).
     */
    public double readDouble(String message) {
        boolean isADouble = false;
        String tekst = null;
        double gelezen = 0.0;
        while (!isADouble) {
            tekst = readString(message);
            if (tekst != null) {
                try {
                    gelezen = Double.parseDouble(tekst);
                    isADouble = true;
                } catch (NumberFormatException nfe) {
                    isADouble = false;
                }
            } else {
                isADouble = true;
                gelezen = 0.0;
            }
        }
        return gelezen;
    }

    /**
     * Wanneer je in je programma geen uitvoer meer nodig hebt 
     * MOET je deze bewerking op het SimpleInOutDialog-object uitvoeren.
     * Het programma wordt dan beëindigd.
     */
    public void stop() {
        System.exit(0);
    }

}
.

役に立ちましたか?

解決

You get much cleaner code if you think in complete reservations instead of individual lines:

void deleteReservations(String reservationName, BufferedReader input,
      PrintWriter output) throws IOException {
    String date;
    while ((date = input.readLine()) != null) {
      String name = input.readLine();
      String tickets = input.readLine();

      // You can check any part of a reservation here
      // to figure out wether to keep or delete it.
      if (!name.equals(reservationName)) {
        output.println(date);
        output.println(name);
        output.println(tickets);
      }
    }
  }

This will obviously fail on files that are not following the 3-line-block format, but then again, the file is broken anyway.

Sample input based on Sergey Brenner's answer:

08:00
Niel Butaye
1
09:00
dean koontz
2
10:00
stephen king
3

given the name dean koontz outputs:

08:00
Niel Butaye
1
10:00
stephen king
3

他のヒント

Although it's not a fine and safe way to store reservation entities in a text file like you do, I have debugged your code related to manipulating the text file. In your removeLineFromFile() method change your while loop to the code below and it will be done.

boolean go = true;
while ( go )
{
    String temp = "";
    for ( int i = 0; i < 3; i++ )
    {
        line = br.readLine();
        if ( line != null )
            temp += line + "\n";
        else
            go = false;
    }

    if ( !temp.trim().contains( lineToRemove ) )
    {
        pw.print( temp );
        pw.flush();
    }
}

I'd recommend put a marker like $$ at the start and at the end of your reservation to delete or sort of a tag for it if possible when you create a file for it. If the location of the reservation in the file is the same always you can iterate through file and check the needed lines to remove.

You have taken the code from here http://www.javadb.com/remove-a-line-from-a-text-file which requires a string as a parameter to be deleted. So you have to know beforehand which exact line has to be removed.

EDIT:

input file

08:00
Niel Butaye
1
09:00
dean koontz
1
10:00
stephen king
1

    public static int  findLineToDelete(String file, String lineToRemove) {
     int lineFound=0;
    try {

      File inFile = new File(file);

      if (!inFile.isFile()) {
        System.out.println("Parameter is not an existing file");
        return -1;
      }

      BufferedReader br = new BufferedReader(new FileReader(file));
      String line = null;

      //Lees het originele bestand en schrijf naar het tijdelijke bestand 
      //Als de lijn == de lijn die we zoeken schrijven we dit niet over
      int i=0;
      while ((line = br.readLine()) != null) {
         i++;
        if (line.trim().equals(lineToRemove)) {  
            System.out.println(i);
          lineFound=i;          
        }
      }

      br.close();

    }
    catch (FileNotFoundException ex) {
      ex.printStackTrace();
    }
    catch (IOException ex) {
      ex.printStackTrace();
    }

  return lineFound;
  }

public static void removeNthLine(String f, int toRemove) throws IOException {

    File tmp = File.createTempFile("tmp", "");

    BufferedReader br = new BufferedReader(new FileReader(f));
    BufferedWriter bw = new BufferedWriter(new FileWriter(tmp));
    int i=0;
    String l=null;
        System.out.println("toRemmove"+toRemove);
    while (null != (l = br.readLine())){
        i++;
        if(i!=toRemove-1&&i!=toRemove&&i!=toRemove+1){
          System.out.println(l);
          bw.write(String.format("%s%n", l)); 
         }
    }

    br.close();
    bw.close();

    File oldFile = new File(f);
    if (oldFile.delete())
        tmp.renameTo(oldFile);

   }
  public static void main(String[] args) {


    int found = findLineToDelete("a.txt", "dean koontz");
    System.out.println(found);
    try{
    removeNthLine("a.txt",found);
    }catch(Exception e){e.printStackTrace();}

  }

hope it helps abit.

The Below Example can easily delete multiple lines from the text File.

Enter file name.

Enter First line no:

Enter no. of lines, you want to delete.

Check below example under comment!

import java.io.BufferedReader;

import java.io.File;

import java.io.FileReader;

import java.io.FileWriter;


public class RemoveLines



{   
public static void main(String[] args)
{

   //Enter name of the file here
    String filename="foobar.txt";

    //Enter starting line here

    int startline=1;

    //Enter number of lines here.
    int numlines=2;

    RemoveLines now=new RemoveLines();
    now.delete(filename,startline,numlines);
}
void delete(String filename, int startline, int numlines)
{
    try
    {
        BufferedReader br=new BufferedReader(new FileReader(filename));

        //String buffer to store contents of the file
        StringBuffer sb=new StringBuffer("");

        //Keep track of the line number
        int linenumber=1;
        String line;

        while((line=br.readLine())!=null)
        {
            //Store each valid line in the string buffer
            if(linenumber<startline||linenumber>=startline+numlines)
                sb.append(line+"\n");
            linenumber++;
        }
        if(startline+numlines>linenumber)
            System.out.println("End of file reached.");
        br.close();

        FileWriter fw=new FileWriter(new File(filename));
        //Write entire string buffer into the file
        fw.write(sb.toString());
        fw.close();
    }
    catch (Exception e)
    {
        System.out.println("Something went horribly wrong: "+e.getMessage());
    }
}
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top