سؤال

ما أحاول القيام به هو حذف حجز قمت بها يبدو الحجز مثل هذا في ملف TXT giveacodicetagpre.

الرمز الذي يجب أن أحذف الحجز هو: giveacodicetagpre.

يحذف فقط اسم صانع الحجز، أحتاج إلى حذف الساعة (08:00) ونوع الحجز (1) أيضا.أي مساعدة؟ giveacodicetagpre.

هل كانت مفيدة؟

المحلول

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