Deleting first line off file

Hello,
I want to remove the first line of a file. Is there any way to do that
without reading the whole file and putting it in a huge string?
Something like setting the "begining of file marker" (does that
exist?). I've looked in the "advanced file function" and can't find a
way to do it.
Any suggestion?
Thanks a lot!!
Vincent

I don't see any Read File by Lines vi in LV7.1.  Maybe it exists in LV 8.  However there is a Read Lines from File vi but it does not produce an array of lines (at least not in LV 7.1).  You can use the Read Lines from File vi and set the number of lines to 1.  The output mark after read is now set to point to the second line.  You can use this as an input to start of read offset on your next read call.  This vi will open the file, read, then close the file.  Calling it a second time will open the file again, read, then close again.
Another way is to open the file using Open/Create/Replace File.  Then use Read File and set the Line Mode input to True.  This will read the first line.  A second Read File call will then begin reading at the second line without having to wire any offsets.  After reading all that you want, you close the file.  One open, several reads, one close.  This is more efficient.
Message Edited by tbob on 03-06-2007 03:03 PM
- tbob
Inventor of the WORM Global
Attachments:
ReadLines.png ‏4 KB

Similar Messages

  • Arraylist only reading first line of file

    I am reading a text file using an arraylist. my file has a single value on each line e.g.
    2
    3
    4
    5
    however this method is only reading only the first line of each file. is it because of this statement:
    String s1[] = number.split("\\s");
    I would like to change the method so its not expecting numbers in a single line.. but reads each line and adds it to the collection... how can I do that?
    here is getData method that gets the file and processes it.
         public static List<Integer> getData(String Filename) {
              List<Integer> array1 = null;
              // BufferedReader for file reverse.txt
              try {
                   array1 = new ArrayList<Integer>();
                   BufferedReader bf = new BufferedReader(new FileReader(Filename));
                   String number = bf.readLine();
                   String s1[] = number.split("\\s");
                   for (int i = 0; i < s1.length; i++)
                        array1.add(Integer.parseInt(s1));
              } catch (Exception e) {
                   e.printStackTrace();
              return array1;

    Faissal wrote:
    while(bf .ready()){
    readline() will return null if the end of the stream has been reached. ([http://java.sun.com/javase/6/docs/api/java/io/BufferedReader.html]). This condition can be used to determine when to stop reading thereby ensuring that all lines have been read.
    EDIT:
    Here's a code snippet from [Java Developers Almanac|http://www.exampledepot.com/egs/java.io/ReadLinesFromFile.html]: notice how they close() the stream when they're finished with it.

  • File Sender Adapter Skip first line in file

    Hello to all,
    I'm trying to read a file (nfs) using the file adapter.
    The szenario works fine, but I need to skip the first line in the txt file (header line)
    I tried parameter documentSkipFirstRows, without success.
    Any ideas?
    Regards Christian

    Hi Kaiser,
    May be the syntax problem.
    use like this...
    xml.documentSkipFirstRows     1
    Syntax is
    xml.documentSkipFirstRows=<noOfRows>
    for more info refer this link..
    http://saphelp.border-states.com/EN/0d/00453c91f37151e10000000a11402f/frameset.htm
    Verify this...
    Thanks.

  • Delete some lines from file...

    Hi,
    I'm using this code
          File file = new File(sFile);
          if (!file.exists())
            file.createNewFile();
          fout = new PrintWriter(new OutputStreamWriter(new FileOutputStream(sFile , true)) , true);
    PrintWriter fout;
    ...When file has more then (let's write) 1000 lines, I want to delete last 100 from file.
    Can someone help me to do that? Can you posto me a part of code which will done that?
    Thanks.

    If you want to use "standard" (serial) IO, which reads from the beginning of the file, create a line counter, read the file line-by-line, and when the file size limil is reached, close the file - remaining lines will be truncated from the file.
    If the file lines are all equal in length, then you can use the RandomAccessFile methods to directly seek to the desired line and delete lines after that point using the class methods - see the seek and setLength methods.

  • I am editing an e book. How do I delete a first line indent?

    In a 'Pages' e-book, how can I delete first-line indent on every paragragh?

    Use can use an intro media image. The first time the ibook is open it will start with that page. However, remember that any other time the ibook is open it will show the last page viewed. This is a behavior that can't be changed.

  • Removing first line in text file... Memory and HD concern

    Hello all,
    I want to remove the first line of a text file. This is easy... One way
    to do it, is to find the first "end of line" caracter, strip the string
    and re-write the sting in file with the "strip to sreadsheet" VI.
    Since the file can be quite large (about 120000 lines), is this a good
    way to do it. Will it re-write all the line or just moving the "begin
    of file" pointer to the second line? If it re-write the whole file,
    this option is not very good since I could have to do this operation
    quite often. (I want the file to be a kind of circular buffer / backup).
    What do you think is the best way to do this?
    Thanks!
    Vincent

    I think you would have to read in all the data and write it to a new file, you could either keep the data in RAM or simply write to another file then delete the original, and then rename the temp one.  So obviously that is a lot of data and memory.
    My main question is are you trying to use a text file as a circular buffer?  If so can you tell us more about the data, ie is it strings of a constant length?  Does a user ever need to read the file or could we head binary?
    A solution would be to truly make the file a binary file, so you could actually seek through the file easier, and maybe make the first data chunk the location of the most recent write.  The obvious danger is then writing over existing data.  This solution is still risky because of the data writes.
    You may want to look at some of the other file formats like HWS which maintains a hierarchy of data for you so you can simply add and remove data from it.  However, a user will not be able to easily read it.

  • Remove 1st & 2nd lines in 1st file, and 1st line in 2nd file. I want the headers to be the first line after the script runs!

    I have two files that look like this (Notepad++):
    In the first file, which has a date as a name and always ends in 'COV', I want to remove the 1st & 2nd lines.  All lines end in LF (LineFeed).  In the 2nd file, which has a date as a name and always ends in 'RSK', I want to remove the 1st line. 
    Basically I want only the headers.  I'm working with the code below.  I've tried several different iterations of
    reader.ReadLine().Skip(1);
    reader.ReadLine().Skip(2);
    reader.ReadLine().Skip(3);
    It never really gives me what I want, so I can't tell what's going on here.  I guess I'm missing something simple, but I don't know what.  Any ideas, anyone?
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.IO;
    using System.Diagnostics;
    namespace ConsoleApplication1
    class Program
    static void Main(string[] args)
    string sourceDirectory = @"C:\Users\rshuell\Desktop\Downloads\Files";
    try
    var txtFiles = Directory.EnumerateFiles(sourceDirectory);
    foreach (string currentFile in txtFiles)
    if (currentFile.Contains("COV"))
    var items1 = new LinkedList<string>();
    using (var reader = new StreamReader(currentFile))
    reader.ReadLine().Skip(2); // skip 2lines
    string line;
    while ((line = reader.ReadLine()) != null)
    items1.AddLast(line.Replace("\"", ""));
    File.WriteAllLines(currentFile, items1);
    else
    var items2 = new LinkedList<string>();
    using (var reader = new StreamReader(currentFile))
    reader.ReadLine().Skip(1); // skip one line
    string line;
    while ((line = reader.ReadLine()) != null)
    items2.AddLast(line.Replace("\"", ""));
    File.WriteAllLines(currentFile, items2);
    catch (Exception ex)
    Knowledge is the only thing that I can give you, and still retain, and we are both better off for it.

    Call the ReadLine() twice if you want to skip the first two lines. Each call results in a single line being read:
    static void Main(string[] args)
    string sourceDirectory = @"C:\Users\rshuell\Desktop\Downloads\Files";
    try
    var txtFiles = Directory.EnumerateFiles(sourceDirectory);
    foreach (string currentFile in txtFiles)
    if (currentFile.Contains("COV"))
    var items1 = new LinkedList<string>();
    using (var reader = new StreamReader(currentFile))
    reader.ReadLine(); //read line 1
    reader.ReadLine(); //read line 2
    string line;
    while ((line = reader.ReadLine()) != null)
    items1.AddLast(line.Replace("\"", ""));
    File.WriteAllLines(currentFile, items1);
    else
    var items2 = new LinkedList<string>();
    using (var reader = new StreamReader(currentFile))
    reader.ReadLine(); // skip one line
    string line;
    while ((line = reader.ReadLine()) != null)
    items2.AddLast(line.Replace("\"", ""));
    File.WriteAllLines(currentFile, items2);
    catch (Exception ex)
    Calling the Skip method on the already read string returned by the ReadLine() method won't help you at all here. By the time you call the Skip method the line has already been read from the file. You must call the ReadLine() method for a new line being read.
    Hope that helps.
    Please remember to close your threads by marking helpful posts as answer and please start a new thread if you have a new question.

  • Delete a line in a .txt file

    Hi, i would delete the first line of a .txt file but i don't understand wich kinf of java.io object i have to use. Now i'm trying to work with BufferedReader in this code:
    BufferedReader in = new BufferedReader(new FileReader(file));
    int len;
    len = in.readLine().length();     
    StringBuffer lineSB= new StringBuffer(in.readLine());
    lineSB.delete(0,lineSB.length());
    PrintWriter out = new PrintWriter(new FileWriter(file));
    out.close();
    in.close();
    ...but the file is cancelled totally. Please help me!

    Here is your code, with comments about what you are doing:
    StringBuffer lineSB= new StringBuffer(in.readLine());
    lineSB.delete(0,lineSB.length()); // delete the entire string buffer (not file)
    PrintWriter out = new PrintWriter(new FileWriter(file)); // creating a new printWriter for an entirely new file with the -name- in string file (no relation to previous file)what you need to do is something like this:
    in.readLine(); // discard the first line
    String s = in.readLine(); // get the next line
    PrintWriter p = new PrintWriter(new FileWriter(newFileName));
    while(in != null) {
      p.out(s); // write each line back out to the new file
      s = in.readLine();
    }Hope this helps.
    - amber

  • During file read it is cutting first character of first line

    This program has a file 7918.txt
    with contents
    user=ry;checkout=yes;checkin=yes
    user=dg;checkout=yes;checkin=yes
    user=nik;checkout=yes;checkin=yes
    user=dg;checkout=yes;checkin=yes
    when i am trying to read it is displaying (or storing it to another file) after cutting first letter of first line.
    ser=ry;checkout=yes;checkin=yes
    user=dg;checkout=yes;checkin=yes
    user=nik;checkout=yes;checkin=yes
    user=dg;checkout=yes;checkin=yes
    import java.util.*;
    import javax.servlet.*;
    import javax.servlet.http.*;
    import java.io.*;
    public class txtSearch2 extends HttpServlet {
    // PrintWriter out =null;
    public void doGet(HttpServletRequest req, HttpServletResponse res)
    throws ServletException, IOException
         PrintWriter out = res.getWriter();
         String user="nik";
         String filename="7918";
         try{
                   BufferedReader br =null;
                   File tt = new File("myserver/servletclasses/"+filename+".txt");
    int ind=0;
                   int lno=0;
                   int i=0;
              if( tt.exists() ){
                   br = new BufferedReader(new FileReader("myserver/servletclasses/"+filename+".txt"));
                   String s, s2 = new String();
                   while(br.read()!=-1)
                        while((s = br.readLine())!=null)
                             out.println("S_______ "+s);
                        s2 += s + "\n";     
                             out.println("S222_______ "+s2);
                             if (s.indexOf(user) > -1)
                             { out.println("LINE NO "+lno);
                             ind=lno;
                             out.println("INDEX "+ind);
                             lno++;
              BufferedWriter      bw
              = new BufferedWriter(
              new OutputStreamWriter(new
              FileOutputStream("myserver/servletclasses/"+filename+"x.txt")));
              bw.write(s2);
              out.println("SSSSSSSSSSSSSSSS@@@@@@@@@@@@@@@@@@222222"+s2);
              bw.flush();
    br.close();     
              bw.close();
    out.println(" INDNO "+ind);
    out.println("LINE NO3///////////////////////// "+lno);
         }catch(FileNotFoundException f)
         catch(IOException io)
    Thanks

    Look carefully at your code:
    while(br.read()!=-1)
    while((s = br.readLine())!=null)See where you chop off the first character?

  • Need help with java File IO ( Removing the first line from a file )

    Hi guys ,
    I am currently doing a project in which I need to extract out the values from the second line of a file to the end. The question is how do I ignore the first line ??
    I thought of two possible answers myself. One is to use randomaccessfile to read and rewrite. But the file may be HUGE so storing the whole file in memory is not a very good idea.
    Second is to jump to second line before doing while ((str = in.readLine()) != EOL) ... or just delete the first line from the file. Can anyone suggest a better solution or show me some sample codes ? Thanks.
    regards
    billyam

    Just skip the first line (bufferedReader.readLine()), add a comment, and then handle the rest of your file

  • RFFOCA_T: DME with file descriptor in first line (RBC)

    Hi All,
    I've customized the automatic payment run for a company located at Canada - including generated DME- file by the report RFFOCA_T. The DME file looks good - but sadly the house bank (RBC, Royal Bank of Scotland) is expecting two things different:
    "Different formats now exist for the Royal Bank and CIBC from the default CPA-005 specification.
    u2022 Type 'A' and 'Cu2019 records have been modified to handle RBC and CIBC
    u2022 A parameter was added to job submission to request the bank type
    This process has been revised to include two headers as part of the tape_header code segment.
    u2022 The first header must be the first line in the file and appear in the following format: $$AAPDCPA1464[PROD]NL$$
    u2022 The second header (positions 36 to 1464) must be filled with blanks, not zeros"
    (taken from "SCT Banner, Finance, Release Guide - January 2005, Release 7.0")
    In our DME-file the second header (position 36 to 1464) is correct, but the first header is completely missing.
    RBC wrote me in an email:: "The first line of the file needs the file descriptor ($$AAPDCPA1464[PROD]NL$$). The date format and the client number is correct. When the $$ file descriptor has been added please upload the TEST file":
    I could not find any solution at SAP/ OSS - can anybody help, please?
    Thanks a lot!
    Sandra.

    Hi Revi,
    I'm not sure if I understand you in the right way.
    I do not have a problem only with the $$ at the beginning. The whole first expected line as the file descriptor is missing. As we saw in the report code, it's not considered. At least I hope, there is a simple solution - like an update or else - but maybe we need to enlarge the report itself by a programmer?
    Thanks,
    Sandra

  • 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!!!!!!

  • I have an Iphone 4, I have music files that appear on my phone that I want to delete, when I link it to my computer the songs on the phone will not appear in Itunes so I can delete them, Is there any way to delete these song off the phone without going th

    I have an Iphone 4, I have music files that appear on my phone that I want to delete, when I link it to my computer the songs on the phone will not appear in Itunes so I can delete them, Is there any way to delete these song off the phone without going through Itunes?

    Nope, it either needs to be plugged in or turned on with the power button.
    A replacement iPhone 4 is $149, but at least the whole phone is replaced.

  • Trying to omit first line of CSV file (the header)

    Hello everybody,
    Newbie here havin a lil problem. I have this program below that reads in a CSV file. My test CSV file has the follow structure:
    ID, LastName, FirstName, Phone, Email,
    2345, Yez, Wei do, 456-789-0123, [email protected],
    2744, Avanto, Aldo, 562-593-6500, [email protected],
    1212, Dewy, Cheatem, 123-456-7890, [email protected],
    1234, No, Wei Foo, 123-456-7890, [email protected],
    The first line is my header. (here is the heart of my problem)
    I have the program reading in the file and the it sorts it. The problem i have is that the first line, my header gets sorted with everything else. Here is my feable attempt with resulting error:
    import java.io.*;
    import java.util.*;
    public class File2Array {
        public static void main(String[] args)
            File file = new File("person_test1.csv"); //File to read in
            ArrayList persons = (ArrayList) getPersons(file); //call to arraylist
            Collections.sort(persons);
            for (Iterator i = persons.iterator(); i.hasNext(); )
                System.out.println(i.next());
        public static List getPersons(File file)
    //NEW PIECE OF CODE        boolean first = true;
            ArrayList persons = new ArrayList();
            try {
                BufferedReader buf = new BufferedReader(new FileReader(file));
                while (buf.ready()) {
                    String line = buf.readLine();
    //NEW PIECE OF CODE
         while( ( line = buf.readLine() ) != null )
              if( first )
                   first = false;    continue;
    //ORIGINAL IF
         //   if (!line.equals("") )
    //NEW IF
                    if (line != null && !line.equals("") )
    //END OF NEW CODE
                         StringTokenizer tk = new StringTokenizer(line, ",");
                         ArrayList params = new ArrayList();
                         while (tk.hasMoreElements())
                             params.add(tk.nextToken());
                         Person p = new Person(
                                 (String) params.get(0),
                                 (String) params.get(1),
                                 (String) params.get(2),
                                 (String) params.get(3),
                                 (String) params.get(4));
                         persons.add(p);
            } catch (IOException ioe)
                System.err.println(ioe);
            return persons;
    class Person implements Comparable
        private String ID;
        private String LastName;
        private String FirstName;
        private String Phone;
        private String Email;
        public Person(
            String ID,
            String LastName,
            String FirstName,
            String Phone,
            String Email)
            if (FirstName==null || LastName==null)
                throw new NullPointerException();
            this.ID = ID;
            this.LastName = LastName;
            this.FirstName = FirstName;
            this.Phone = Phone;
            this.Email = Email;
        public String toString()
            StringBuffer sb = new StringBuffer ();
            sb.append( ID );
            sb.append(" ");
            sb.append( LastName );
            sb.append(" ");
            sb.append( FirstName );
            sb.append(" ");
            sb.append( Phone );
            sb.append(" ");
            sb.append( Email );
            sb.append(" ");
            return sb.toString();
        public boolean equals(Object o)
            if (!(o instanceof Person))
                return false;
            Person p = (Person)o;
            return p.FirstName.equals(FirstName) &&
                   p.LastName.equals(LastName);
        public int hashCode()
            return 31*FirstName.hashCode() + LastName.hashCode();
        public int compareTo(Object o)
            Person p = (Person)o;
            int lastCmp = LastName.compareTo(p.LastName);
            return (lastCmp!=0 ? lastCmp :
                    FirstName.compareTo(p.FirstName));
    this code compiles and runs but does not produce any output and I don't understand why.
    Question: What is the proper way to have the code omit the first line of a CSV file??
    By the way I do have another file called person.java that goes with this but I didn't think I had to post it.
    Also am I posting correctly? Am I putting in too much code??
    Than you!!

    Hot diggity! jverd,
    I got it to work!! here's what I did all thanks to you :-)
    ArrayList persons = new ArrayList();
            try {
                BufferedReader buf = new BufferedReader(new FileReader(file));
                //read through file and populate array
                //while (buf.ready()) {
                    String firstline = buf.readLine();  //gets header, renamed line to firstline
                    String line;                  //added this line     
                    System.out.println(firstline);     //added this to print out firstline     
         //try this
              while( ( line = buf.readLine() ) != null )
              /*{                    //commented out this portion
              if( first )
                   first = false;    continue;
              //end try this                
                    //if (line != null && !line.equals("") )     //down to here
                    if (!line.equals("") )          //added this
                         StringTokenizer tk = new StringTokenizer(line, ",");
                         ArrayList params = new ArrayList();
                         while (tk.hasMoreElements())
                             params.add(tk.nextToken());
                         Person p = new Person(
                                 (String) params.get(0),
                                 (String) params.get(1),
                                 (String) params.get(2),
                                 (String) params.get(3),
                                 (String) params.get(4));
                         persons.add(p);
                      }                       

  • The first line in a file is supressed

    hi all,
    i have a really weird problem.
    i have a file with a lot of data and i am using a file adapter with file content conversion to parse it.
    the file adapter is a sender one.
    the problem come when i do read the file and then it ignore the first line of the file.
    all the lines from the second one forward is shown in SXMB_MONI but the first line of the file isn't.
    i can't seem to figure out what the problem is, i tryed looking for some kind of attribute in the file adpater but had no luck.
    could you please help me?
    btw,
    the file structure is: header,1,body1,<wildcard>,body2,<wildcard>
    Edited by: Roi Grossfeld on Oct 29, 2008 4:24 PM

    Recordset Structure: H1,1,B1,<wildcard>,B2,<wildcard>
    Key Field Name: RecordType
    H1.fieldFixedLengths 6,2,8,1,1,3,30,5
    H1.fieldNames FileNo,RecordType,TransmissionDate,Car_Truck,BU,MD,FileName,Count
    H1.keyFieldValue H1
    B1.fieldFixedLengths 6,2,10,27,8,8,4,5,3,11,9,9,11,11,9,9,7,9,11
    B1.fieldNames FileNo,RecordType,InvoiceNumber,VesselName,MMSEShipmentDate,PlanArrivalDate,DeliveryPlace,Units,Currency,ModelPriceAmount,OptionPriceAmount,ColourPriceAmount,REPriceAmount,TotalPriceAmount,FreightChargeAmount,InsuranceFeeAmount,MiscellaneousAmount,VATAmount,GrandTotalAmount
    B1.keyFieldValue B1
    B2.fieldFixedLengths 6,2,10,12,12,12,5,6,12,3,3,3,4,17,7,7,12,8,5,3,9,7,7,9,9,7,9,4,20
    B2.fieldNames FileNo,RecordType,InvoiceNumber,MDOrderNumber,MMSEOrderNumber,MMSECaseNumber,ModelYear,BodyType,Model,ExteriorColourCode,InteriorTrimColourCode,OptionCode,RearEquipment,VehicleIdentificationNumber,ChassisModel,CSequenceNumber,EngineModel,ESequenceNumber,KeyNumber,Currency,UnitModelPrice,UnitOptionPrice,UnitColourPrice,UnitRearEquipmentPrice,UnitTotalPrice,UnitVATAmount,UnitTotalVAT,VATRate,VATNumber
    B2.keyFieldValue B2
    ignoreRecordsetName true
    Edited by: Roi Grossfeld on Oct 29, 2008 4:39 PM

Maybe you are looking for