开发者

Displaying first and last lines of Text File?

开发者 https://www.devze.com 2023-02-23 18:15 出处:网络
I have a GUI program that开发者_如何学运维 I\'m using to navigate a text file. It\'s nothing too complex, just the ability to browse the file and add new information to it. However I would also like t

I have a GUI program that开发者_如何学运维 I'm using to navigate a text file. It's nothing too complex, just the ability to browse the file and add new information to it. However I would also like to be able to identify the first line in the text file, as well as the last. Basically if I have a text file that looks like this:

  • California, West, 1981, 115, 25.99
  • New York, East, 1991, 120, 19.95

I wish to, when a button is pushed saying first - the text California comes up, identifying the first line in the text. But I just want California to display, not the rest of the info on the first line. I wish to do this for the last line to, in the same style.

I'm using the FileReader and FileBuffer with StringTokenizer. Is there a way of just calling the first token of the first line and the first token of the last line? Thanks for the help!


to get the first token of line you can do

String line = "California, West, 1981, 115, 25.99"
String firstToken = line.split(",")[0]

to get the lastline i would iterate the whole file and store it in the List and get the last element , something like:

String line ="";
List<String> list = new ArrayList<String>();
          while((line = fileReader.readLine())!= null){
                 list.add(line)
         }
 list.get(0) // first line
 list.get(list.size()-1) // last line


The provided answers should work well in most (the vast majority) of situations. But for truly enormous input files, it might make sense to take a different approach using a RandomAccessFile (RAF).

Using a RAF, read the first bytes until hitting a new line character (for the first line), then seek backwards from the end of the RAF to find the last new line, and read from there until the end (for the last line).

It is even easier if the lines are fixed column width (FCW), but this data is CSV. For FCW, you can calculate where the last line will begin knowing the file size and line width (length), and seek directly to that point.


This is very old question but right now we have a easy way todo this and I did not found any example of this. I am giving a new answer: I am using Java 11, but maybe is available in Java 8, have to check.

Long lines = Files.lines(Paths.get(file)).count();
String first = Files.lines(Paths.get(file)).findFirst().get();
String last = Files.lines(Paths.get(file)).skip(lines - 1).findFirst().get();


A sample how to find out the desired string

Read the file using stream reader

  streamreader sr=new streamreader("Your.txt");
  while(sr.peek()>=0)
  {
     string strLine=sr.readLine();
      if(strline.startswith("California"))
      {
         //Dispaly it
       }
          if(strline.startswith("NewYork"))
          {
             //Display it
          }
    }


Is there no way to read it from the text file?

If the intervening lines are irrelevant, you can read the first line and scan to the last, without needing to accumulate a collection.

import java.io.BufferedReader;
import java.io.FileReader;

/** @see http://stackoverflow.com/questions/5614004 */
public class FirstLastTest {

    private static String first, last, line;

    public static void main(String[] args) throws Exception {
        BufferedReader in = new BufferedReader(new FileReader(args[0]));
        first = in.readLine();
        while ((line = in.readLine()) != null) {
            if (line != null) {
                last = line;
            }
        }
        System.out.println(first + "\n" + last);
    }
}
0

精彩评论

暂无评论...
验证码 换一张
取 消