How to delete the specified line in file?

How to delete the specified line in file? In case of deleting a specified line in a file, how to do?
Line 1
Line 2
Line 3
Line 4
Line 5
The case is a file including the above content. Now I wanna to delete the "Line 3" and how to realize the action in Java?

An alternative solution can be :
import java.io.LineNumberReader;
import java.io.IOException;
import java.io.File;
import java.io.FileReader;
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.PrintWriter;
public class LineDeleter {
public static void main(String args[]){
try {
//suppose you want to delete line 3
     int lineToBeDeleted = 3;
     File f = new File("line.txt");
     long fileSize = f.length();
//Wrap the FileReader with a LineNumberReader. It will help you
//identify the lines.
LineNumberReader lnr = new LineNumberReader( new FileReader(f));
//Wrap the FileWriter object with BufferedWriter object. Create it with the buffersize
//equal to the file size.
     BufferedWriter bw = new BufferedWriter(new FileWriter(new File("line1.txt")),(int)fileSize);
//Wrap BufferedWriter object with PrintWriter so that it allows you
//to print line by line
PrintWriter pw = new PrintWriter(bw);
     String s=null;
     while ( (s=lnr.readLine())!=null ){
          System.out.println(s);
          int lineNumber = lnr.getLineNumber();
//match the line number
          if(! (lineNumber==lineToBeDeleted)){
               pw.println(s);
          pw.flush();
          lnr.close();
          pw.close();
     catch(Exception e){System.out.println(e);}
If you want you can rename the line1.txt to the original file name.
I hope this helps.Good luck!!!!!!

Similar Messages

  • How to delete the horiz line of addresses beneath the address bar

    How to delete the horiz line of addresses beneath the address window. They are not affected by the "delete recent sites" tool.

    Do you mean the tab bar?
    See [[Tabbed browsing]]

  • How to delete the logical lines in JTextArea

    Hi all,
    Now that I know how to find the logical line count in JTextArea as
    I found the following in the forum.
    public static int getLineCount (JTextArea _textArea)
    boolean lineWrapHolder = _textArea.getLineWrap();
    _textArea.setLineWrap(false);
    double height = _textArea.getPreferredSize().getHeight();
    _textArea.setLineWrap(lineWrapHolder);
    double rowSize = height/_textArea.getLineCount();
    return (int) (_textArea.getPreferredSize().getHeight() / rowSize);
    I want to delete the 4th line to the last line and append ... at the 4th, if the getLineCount exceeds 3. Does any body know how to do so?
    The intention is for the multiline tooltip as I just want to show
    the first three logical line and ... if the string is too long.
    Thanks
    Pin

    The code looks good to me. The only thought I have is that the y coordinate for the rowThree point is wrong and is referencing row four.
    I've been playing around with using a JTextArea as a renderer for a JTable. I have it working so that "..." appear when the text exceeds 2 rows. Try clicking on "B" in the letter column and then the update cell button a few times to add text. My code is slightly different than yours.
    import java.awt.*;
    import java.awt.event.*;
    import java.util.*;
    import javax.swing.*;
    import javax.swing.table.*;
    public class TestTable extends JFrame
         private final static String LETTERS = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
         JTable table;
         Vector row;
         public TestTable()
              Object[][] data = { {"1", "A"}, {"2", "B"}, {"3", "C"} };
              String[] columnNames = {"Number","Letter"};
              DefaultTableModel model = new DefaultTableModel(data, columnNames);
              table = new JTable(model)
                   public String getToolTipText( MouseEvent e )
                        int row = rowAtPoint( e.getPoint() );
                        int column = columnAtPoint( e.getPoint() );
                        if (row == 0)
                             return null;
                        else
                             return row + " : " + column;
              table.setRowSelectionInterval(0, 0);
              table.setColumnSelectionInterval(0, 0);
              table.setRowHeight(0,34);
              table.setRowHeight(1,34);
              table.setRowHeight(2,34);
              table.setDefaultRenderer(Object.class, new TextAreaRenderer(2));
              JScrollPane scrollPane = new JScrollPane( table );
              getContentPane().add( scrollPane );
              JPanel buttonPanel = new JPanel();
              getContentPane().add( buttonPanel, BorderLayout.SOUTH );
              JButton button2 = new JButton( "Update Cell" );
              buttonPanel.add( button2 );
              button2.addActionListener( new ActionListener()
                   public void actionPerformed(ActionEvent e)
                        int row = table.getSelectedRow();
                        int column = table.getSelectedColumn();
                        String value = (String)table.getValueAt(row, column);
                        value += value;
                        table.setValueAt( value, row, column );
                        DefaultTableModel model = (DefaultTableModel)table.getModel();
                        model.fireTableCellUpdated(row, column);
                        table.requestFocus();
         public static void main(String[] args)
              TestTable frame = new TestTable();
              frame.setDefaultCloseOperation( EXIT_ON_CLOSE );
              frame.pack();
              frame.setVisible(true);
         private class TextAreaRenderer extends JTextArea implements TableCellRenderer
              public TextAreaRenderer(int displayRows)
                   setRows(displayRows);
                   setLineWrap( true );
              public Component getTableCellRendererComponent(JTable table,
                                             Object value,
                                             boolean isSelected,
                                             boolean hasFocus,
                                             int row,
                                             int column)
                   setText( value.toString() );
                   Dimension d = getPreferredSize();
                   int maximumHeight = getRows() * getRowHeight();
                   if (d.height > maximumHeight)
                        setSize(d);
                        int offset = viewToModel( new Point(d.width, maximumHeight - 1) );
                        replaceRange( "...", offset-3, getDocument().getLength() );
                   return this;
    }

  • How to delete the beginning of a file?

    Hi,
    is there a way to delete the beginning of a file, or do I have to copy the rest of the file and create a new one and then delete the old one?
    Lets say my file contains "ThisIsMyFile" and I want to delete "This", so that my new file contains "IsMyFile", how can I do this?
    thanx

    You have to copy.

  • How To delete the Chosen line from the Table Control

    Hi Friends,
      i am new to Module Pool Programming , i developed a Table Control in input mode and i am getting data also into that table control. my requirement is that i want to delete the current chosen line from that table control. please help me out.

    HI
    GOOD
    GO THROUGH THIS REPORT
    REPORT demo_dynpro_tabcont_loop_at.
    CONTROLS flights TYPE TABLEVIEW USING SCREEN 100.
    DATA: cols LIKE LINE OF flights-cols,
    lines TYPE i.
    DATA: ok_code TYPE sy-ucomm,
          save_ok TYPE sy-ucomm.
    DATA: itab TYPE TABLE OF demo_conn.
          TABLES demo_conn.
    SELECT * FROM spfli INTO CORRESPONDING FIELDS OF TABLE itab.
    LOOP AT flights-cols INTO cols WHERE index GT 2.
      cols-screen-input = '0'.
      MODIFY flights-cols FROM cols INDEX sy-tabix.
    ENDLOOP.
    CALL SCREEN 100.
    MODULE status_0100 OUTPUT.
      SET PF-STATUS 'SCREEN_100'.
    DESCRIBE TABLE itab LINES lines.
    flights-lines = lines.
    ENDMODULE.
    MODULE cancel INPUT.
      LEAVE PROGRAM.
    ENDMODULE.
    MODULE read_table_control INPUT.
      MODIFY itab FROM demo_conn INDEX flights-current_line.
    ENDMODULE.
    MODULE user_command_0100 INPUT.
      save_ok = ok_code.
      CLEAR ok_code.
      CASE save_ok.
        WHEN 'TOGGLE'.
          LOOP AT flights-cols INTO cols WHERE index GT 2.
            IF  cols-screen-input = '0'.
              cols-screen-input = '1'.
            ELSEIF  cols-screen-input = '1'.
              cols-screen-input = '0'.
          ENDIF.
      MODIFY flights-cols FROM cols INDEX sy-tabix.
    ENDLOOP.
        WHEN 'SORT_UP'.
          READ TABLE flights-cols INTO cols WITH KEY selected = 'X'.
          IF sy-subrc = 0.
            SORT itab STABLE BY (cols-screen-name+10) ASCENDING.
            cols-selected = ' '.
      MODIFY flights-cols FROM cols INDEX sy-tabix.
          ENDIF.
        WHEN 'SORT_DOWN'.
          READ TABLE flights-cols INTO cols WITH KEY selected = 'X'.
          IF sy-subrc = 0.
            SORT itab STABLE BY (cols-screen-name+10) DESCENDING.
            cols-selected = ' '.
      MODIFY flights-cols FROM cols INDEX sy-tabix.
          ENDIF.
        WHEN 'DELETE'.
          READ TABLE flights-cols INTO cols
                                  WITH KEY screen-input = '1'.
          IF sy-subrc = 0.
            LOOP AT itab INTO demo_conn WHERE mark = 'X'.
              DELETE itab.
    ENDLOOP.
          ENDIF.
    ENDCASE.
    ENDMODULE.
    CHANGE THE CODE AS PER THIS LIGIC.
    THANKS
    MRUTYUN

  • How to delete the standby archive log files in ASM?

    Hi Experts
    we have a realtime downstream replication that is using the a location in ASM to put the shipped logs files.
    set up by
    ALTER SYSTEM SET LOG_ARCHIVE_DEST_2='LOCATION=+BOBOASM/NANPUT/standbyarchs/
    VALID_FOR=(STANDBY_LOGFILE,PRIMARY_ROLE)' Scope=BOTH;
    What shall i do to clean up those files ?
    Any procedure or script to do that?
    Thanks

    Hello Haggylein
    check this out, seems to work
    --- redologs used or not?
    ---- when purgeable we can delete it
    COLUMN CONSUMER_NAME HEADING 'Capture|Process|Name' FORMAT A15
    COLUMN NAME HEADING 'Archived Redo Log|File Name' FORMAT A25
    COLUMN FIRST_SCN HEADING 'First SCN' FORMAT 99999999999
    COLUMN NEXT_SCN HEADING 'Next SCN' FORMAT 99999999999
    COLUMN PURGEABLE HEADING 'Purgeable?' FORMAT A10
    SELECT r.CONSUMER_NAME,
    r.NAME,
    r.FIRST_SCN,
    r.NEXT_SCN,
    r.PURGEABLE
    FROM DBA_REGISTERED_ARCHIVED_LOG r, DBA_CAPTURE c
    WHERE r.CONSUMER_NAME = c.CAPTURE_NAME and PURGEABLE = 'YES';
    -- Now the script
    -- to be executed on the downstream database
    -- generate the list of logs to be purged and executed in a ksh script
    -- sqlplus "/as sysdba" @$HOME/bin/generate_list.sql
    SET NEWPAGE 0
    SET SPACE 0
    SET LINESIZE 150
    SET PAGESIZE 0
    SET TERMOUT OFF
    SET ECHO OFF
    SET FEEDBACK OFF
    SET HEADING OFF
    SET MARKUP HTML OFF SPOOL OFF
    spool list_purgeable_arch_redologs.ksh
    SELECT 'asmcmd ls ' || r.NAME
    FROM DBA_REGISTERED_ARCHIVED_LOG r, DBA_CAPTURE c
    WHERE r.CONSUMER_NAME = c.CAPTURE_NAME and PURGEABLE = 'YES';
    spool off
    exit
    # eventually we can call it from a script
    # !ksh
    # delete of the shipped redologs
    # to be performed on node 2
    # not to be used on
    $HOME/bin/export ORACLE_SID=+ASM2
    ./list_purgeable_arch_redologs.ksh
    exit

  • To delete the last line of the internal table

    How to delete the last line of the internal table.???????
    The list which gets displayed from the internal table adds a dummy line at the last which shows zeros and zeros.all the otheer selections are perfect.i just want to delete the last line which comes as zero zero.is there any way to do it...

    Quite Easy......Use Describe command to Count the Total Number of Table Lines, and then Delete the Last Line using Index.
    Data L like sy-tabix.
    Describe Table Itab Lines L.
    Delete itab index L.

  • How to delete string or line from unix file(dataset) of application server

    Hi  All,
    After transfer workarea information or all records into dataset(unix file). When I see the file in application server automatically the last line is shown a blank line. I am not passing any blank line.
    I have tried for single record than also the file generates the last line(2nd line) also a blank line.
    When I m reading the dataset, it is not reading the last blank line but why it is showing the last blank line?
    How to delete string or line from unix file(dataset) of application server?
    Please give your comments to resolve this.
    Thanks
    Tirumula Rao Chinni

    Hi Rio,
    I faced similar kind of issue working with files on UNIX platform.
    The line is a line feed to remove it use
    DATA : lv_carr_linefd TYPE abap_cr_lf VALUE cl_abap_char_utilities=>cr_lf. 
      DATA : lv_carr_return TYPE char1,                                   
             lv_line_feed   TYPE char1.                                          
      lv_line_feed   = lv_carr_linefd(1).
      lv_carr_return = lv_carr_linefd+1(1).
    Note: IMP: The character in ' ' is not space but is a special
    character set by pressing ALT and +255 simultaneosly
      REPLACE ALL OCCURRENCES OF lv_line_feed IN l_string WITH ' '.
      REPLACE ALL OCCURRENCES OF lv_carr_return IN l_string WITH ' '.

  • How to delete the record in the file present in the application server?

    Hi,
      I have two questions.
      i) How can I delete a record based on some condition in the recordx in the file that is present in the application server?
      ii) How can I lock the users whiel one user is accessing the file on the application server?
    Thanks in advance.
    Suvan

    Hi,
    If u want a frequent deletion this approach to delete a record from a file will havee unnecesary copy of records from one file to another and deletion of one file and renaming activities.
    Instead what u can do is Add and field del_flag to ur record structure.
    If u want to delete the record from a file just mark this del_flag as 'X'.
    While processing u can have a loop like
    loop at it_XXX where del_flag <> 'X'.
    endloop.
    This will logically delete the record.
    When u r to finish the application at that time only perform this copying / deleting / and renaing activity
    Hope this helps.
    Cheers,
    Nitin

  • How to delete the file with space in name

    Hi
    I want to delete the file "test ex.txt" file.
    i run the following command in command prompt.i can delete the file successfully.
    /bin/rm -f /mnt/"test ex.txt"
    I want to run the command from java.So i am using the following code
    String cmd = "/bin/rm -f /mnt/\"test ex.txt\"";
         Runtime rt = Runtime.getRuntime();
    process = rt.exec(cmd);
    The file was not deleted.
    How to delete the file with space in name?
    Help me

    Use the form of exec that takes an array of command + args.
    arr[0] = "/bin/rm"
    arr[1] = "-f"
    arr[2] = "/home/me/some directory with spaces";Or use ProcessBuilder, which is the preferred replacement for Runtime.exec, and which Runtime.exec calls.

  • How to delete the Cost center line item data

    How to delete the cost center line item data of particular cost center and only one cost center is exisiting for that company code.
    Is there any way to delete the line items in that cost center.
    Can data archiving & deleting can help us..........
    does it have any effect over other cost center data....
    any input needed.........
    regards
    rajesh

    Hi,
    i found 2 reports for you:
    1) CO_TOTAL_WRI - Archiving CO Totals Records   
    2) RKCOITW1     - Archiving CO Line Items: Write Program        
    from 2) is a linlk to customize archiv-parameters
    -> start it with transaction se38 / sa38
    A.

  • How to delete the old schedule line release?

    Hello,
    How to delete the old schedule line release in apo?
    Generally GR has to be carry out  schedule line release  in r/3 which reduces the Schdule line release.
    But i do want do GR against old schdule line release instead i want to delete the old schdule line release.
    Please suggest.
    Regards,
    Sunil Patil

    Sunil ,
    /sapapo/cmds_del  is the tcode to deleted sales scheduling agreement confirmations and releases
    /sapapo/display_conf  is the tcode for displaying sls. sch.agr confirmations and releases
    The above two are in the supply chain collaboration menu
    /sappao/cmds_sc02 is the tcode to delete sales scheduling agreements . This tcode is in the application specific master data menu
    Thanks
    Saradha

  • How to delete the old schedule line release in apo

    How to delete the old schedule line release (from current date) in apo which is having schedule  firmed?
    Please suugest.
    Sunil

    How is it possible to delete old purchasing schedule lines in APO (that do not exist in R/3)?
    Though used successfully before, /SAPAPO/CCR will not reconcile our discrepancy in this case.
    Thanks in advance,
    Jim

  • How to delete the temporary files when we log out from ESS

    Hello expert,
    In my company we are running ESS using ITS server, do you know how to delete the temporary files when we log out from ESS?
    Thanks.

    The temporary files used by ESS. For example paystub pdf file.

  • I got a new wireless connection for my mac and cannot figure out how to delete the last connection service I had. Everytime I shut the computer, the network goes back to the other one. I cannot find the file ANYWHERE

    got a new wireless connection for my mac and cannot figure out how to delete the last connection service I had. Everytime I shut the computer, the network goes back to the other one. I cannot find the file ANYWHERE

    Under Network Preferences, select the WiFi
    click on "Advanced..." button
    Select the network you want to delete from the list and click on "-"
    Click "Ok"
    Click "Apply"
    Well done ;-)
    You may also want to delete the wireless key from Keychain.
    Open Keychain, seach for the old wifi network name, slect it and click delete

Maybe you are looking for

  • Error message when trying to configure

    Until yesterday, we had a pismo connected to the internet via airport and then connected the pismo to an airport base via an ethernet cable. We could then connect our macbook and macpro to the internet via the airport base. It was working grand! Howe

  • File-Jdbc scenario

    Dear Friends,          I am performing Simple File to JDBC scenario. For this I am using MySql. I have designed and configured all the required steps and activated. Now I went to Runtime Work Bench monitoring.. Here in Message monitoring status is "w

  • JTable in JScrollPane, preferred size

    When I put a JTable in a JScrollPane, the JScrollPane seems to want to be very big. How does the scroll pane determine its size? run this code for an example.. import javax.swing.*; public class TestPanel extends JPanel public TestPanel()      add(ne

  • Patch approval error getting from solution manager

    Hi, We are getting error while downloading patch approval from solution manager. As reference below error, I have checked this note 982045 & put valid user id & password of the service market place there but error is getting same. Here following erro

  • Process Control workflow - want to delete logical steps against one SC

    Workflow issue : Process control workflow In my scenario when requestor is creating a SC then workflow goes to buyer for assignment of supplier but when buyer himslef is creating a SC and forgot to attach supplier then workflow goes to error....i che