Having trouble reading files in java - java

I have some trouble reading file in Java.
What a file looks like:
Answer 1:
1. This is an apple
2. Something
Answer 2:
1. This is a cool website
2. I love banana
3. This is a table
4. Programming is fun
Answer 3.
1. Hello World
....
What I want to do is separate them into two items:
One is the Answer number; The other one is list of answers.
So assuming I have a object class called Answer:
String of answer number
List of answers.
This is what I have done so far to debug my code before I put it into object class. But I'm not able to get the correct result
public void reader(String file) throws FileNotFoundException, IOException {
FileReader fR = new FileReader(file);
BufferedReader bR = new BufferedReader(fR);
String line = null;
int count = 0 ;
String blockNum = "";
String printState = "" ;
while ((line = bR.readLine()) != null) {
if(line.contains("Answer")){
//System.out.println("Contain Answer statement: " + line);
count++;
blockNum = line;
printState = "";
}
else{
//System.out.println("No Answer Statement: " + line);
printState += line + " / " ;
}
System.out.println( count + " " + blockNum + " " + printState );
}
// Close the input stream
bR.close();
fR.close();
}
I'm pretty sure I did something stupid while I'm coding. I'm not too sure how to read it so that it will have separate it.
Right now the output looks like this:
1 Answer 1:
1 Answer 1: 1. This is an apple /
1 Answer 1: 1. This is an apple / 2. Something /
2 Answer 2:
2 Answer 2: 1. This is a cool website /
2 Answer 2: 1. This is a cool website / 2. I love banana /
2 Answer 2: 1. This is a cool website / 2. I love banana / 3. This is a table /
2 Answer 2: 1. This is a cool website / 2. I love banana / 3. This is a table / 4. Programming is fun /
3 Answer 3.
3 Answer 3. 1. Hello World /
But I want the output to be something like this:
1 Answer 1: 1. This is an apple / 2. Something /
2 Answer 2: 1. This is a cool website / 2. I love banana / 3. This is a table / 4. Programming is fun /
3 Answer 3. 1. Hello World /

You are printing a line of output for each line of input you read. Try moving the println inside the part of the loop that checks for answer to make sure you print each answer/answer value set only once. E.g.:
if(line.contains("Answer")) {
if (printState != "") {
System.out.println(count + " " + blockNum + " " + printState);
}
...
}
EDIT: You will also need to print when you exit the while loop to make sure you print the last answer/answer value set.

One solution use a flag for printTime as a boolean.
boolean printTime = false;
...
if(line.contains("Answer")) {
if (printTime!= false) {
System.out.println( count + " " + blockNum + " " + printState );
printTime=false;
}
...
}else{
//System.out.println("No Answer Statement: " + line);
printState += line + " / " ;
printTime=true; // you have one answer
}
...
add a little extra print at the end of the while for last answer
that way you can have several printState for one answer in one line.
But correct "java" way of handle this is to create your objects:
List<Answer> listOfAnswer = new LinkedList<Answer>();
Answer answer;
...
if(line.contains("Answer")){
//System.out.println("Contain Answer statement: " + line);
count++;
answer = new Answer(line);
listOfAnswer.add(answer)
}
else{
answer.add(new Answer(line));
}
}
...
and only after print them out :)
System.out.println(listOfAnswer.toString());
Simpler solution is to use a
Map<Integer, LinkedList<String>> answers = new LinkedHashMap<Integer, LinkedList<String>();

The main output issue is that you are printing inside the line-iterating loop (while).
To solve it, you can follow what #Albion answered and change where the print is done inside the while, but as the EDIT on his answer states, there is a flaw and you will have to print an extra time after the loop, in order to get the correct result.
There is an alternative tough, that is to not print it inside the loop at all, which i consider to be the correct approach in your case. To do it, you need little more than using StringBuilder instead of String!
I have also spotted some needless variables, and there is also a flaw in using the if(line.contains("Answer")) method, that is that if "Answer" string appears inside one of the options texts, it will get a true and mess your results, for example:
Answer 1:
1. This is an apple
2. Capitalizing Is The Answer!
3. Something
Will output:
1 Answer 1: 1. This is an apple /
2 2. Capitalizing Is The Answer! 3. Something
In most cases, the best approach to finding a dynamic pattern (as yours is, for it changes the number and, in the last Answer, the ':' with a '.' too) is to use a (pattern) Matcher! I used this: if(line.matches("Answer \\d[\\:\\.]")), and if you are not yet used to it, see the Pattern Docs, as String.matches() is something you will probably use a lot when processing text.
Explaining every single change is a little troublesome, and the code is simple enough for you master after you analyse it, so i'll simply post what my approach would be:
public static void StackAnswer(String file) throws FileNotFoundException, IOException{
BufferedReader br = new BufferedReader(new FileReader(file));
StringBuilder output = new StringBuilder();
int count = 0;
while(br.ready()){
String line = br.readLine().trim();
if(line.matches("Answer \\d[\\:\\.]")){
count++;
output.append(System.lineSeparator()).append(count).append(' ').append(line);
} else {
output.append(" / ").append(line);
}
}
System.out.println(output.toString().trim());
br.close();
}
Good luck!

See working example:
public void reader(String file) throws FileNotFoundException,
IOException {
BufferedReader reader = new BufferedReader(new FileReader(file));
String line = "";
while (reader.ready()) {
line = reader.readLine();
if (!line.contains("Answer")) {
System.out.print(line + " / ");
} else {
System.out.println();
System.out.print(line + " ");
}
}
}

Related

NPE in a do/while loop due to EOF...catching the EOF earlier to avoid the NPE [duplicate]

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 5 years ago.
I have written this program to compare 2 files. They are 500mb to 2.8gb in size and are created every 6 hours. I have 2 files from 2 sources (NMD and XMP). They are broken up into lines of text that have fields separated by the pipe(|) character. Each line is a single record and may be up to 65,000 characters long. The data is about TV shows and movies, showing times and descriptive content. I have determined that any particular show or movie has a minimum of 3 pieces of data that will uniquely identify that show or movie. IE: CallSign, ProgramId and StartLong. The two sources for this data are systems called NMD and XMP hence that acronym added to various variables. So my goal is to compare a file created by NMD and one created by XMP and confirm that everything that NMD produces is also produced by XMP and that the data in each matched record is the same.
What I am trying to accomplish here is this: 1. Read the NMD file record by record for the 3 unique data fields. 2. Read the XMP file record by record and look for a match for the current record in the NMD file. 3.The NMD file should iterate one record at a time. Each NMD record should then be searched for in the entire XMD file, record by record for that same record. 4. Write a log entry in one of 2 files indicating success or failure and what that data was.
I have an NPE issue when I reach the end of the testdataXMP.txt file. I assume the same thing will happen for testdataNMD.txt. I'm trying to break out of the loop right after the readLine since the epgsRecordNMD or epgsRecordXMP will have just reached the end of the file if it at that point in the file. The original NPE was for trying to do a string split on null data at the end of the file. Now I'm getting an NPE here according to the debugger.
if (epgsRecordXMP.equals(null)) {
break;
}
Am I doing this wrong? If I'm really at the end of the file, the readLine ought to return null right?
I did it this way too, but to my limited experience they feel like they are effectively the same thing. It too threw an NPE.
if (epgsRecordXMP.equals(null)) break;
Here's the code...
public static void main(String[] args) throws java.io.IOException {
String epgsRecordNMD = null;
String epgsRecordXMP = null;
BufferedWriter logSuccessWriter = null;
BufferedWriter logFailureWriter = null;
BufferedReader readXMP = null;
BufferedReader readNMD = null;
int successCount = 0;
readNMD = new BufferedReader(new FileReader("d:testdataNMD.txt"));
readXMP = new BufferedReader(new FileReader("d:testdataXMP.txt"));
do {
epgsRecordNMD = readNMD.readLine();
if (epgsRecordNMD.equals(null)) {
break;
}
String[] epgsSplitNMD = epgsRecordNMD.split("\\|");
String epgsCallSignNMD = epgsSplitNMD[0];
String epgsProgramIdNMD = epgsSplitNMD[2];
String epgsStartLongNMD = epgsSplitNMD[9];
System.out.println("epgsCallsignNMD: " + epgsCallSignNMD + " epgsProgramIdNMD: " + epgsProgramIdNMD + " epgsStartLongNMD: " + epgsStartLongNMD );
do {
epgsRecordXMP = readXMP.readLine();
if (epgsRecordXMP.equals(null)) {
break;
}
String[] epgsSplitXMP = epgsRecordXMP.split("\\|");
String epgsCallSignXMP = epgsSplitXMP[0];
String epgsProgramIdXMP = epgsSplitXMP[2];
String epgsStartLongXMP = epgsSplitXMP[9];
System.out.println("epgsCallsignXMP: " + epgsCallSignXMP + " epgsProgramIdXMP: " + epgsProgramIdXMP + " epgsStartLongXMP: " + epgsStartLongXMP);
if (epgsCallSignXMP.equals(epgsCallSignNMD) && epgsProgramIdXMP.equals(epgsProgramIdNMD) && epgsStartLongXMP.equals(epgsStartLongNMD)) {
logSuccessWriter = new BufferedWriter (new FileWriter("d:success.log", true));
logSuccessWriter.write("NMD match found in XMP " + "epgsCallsignNMD: " + epgsCallSignNMD + " epgsProgramIdNMD: " + epgsProgramIdNMD + " epgsStartLongNMD: " + epgsStartLongNMD);
logSuccessWriter.write("\n");
successCount++;
logSuccessWriter.write("Successful matches: " + successCount);
logSuccessWriter.write("\n");
logSuccessWriter.close();
System.out.println ("Match found");
System.out.println ("Successful matches: " + successCount);
}
} while (epgsRecordXMP != null);
readXMP.close();
if (successCount == 0) {
logFailureWriter = new BufferedWriter (new FileWriter("d:failure.log", true));
logFailureWriter.write("NMD match not found in XMP" + "epgsCallsignNMD: " + epgsCallSignNMD + " epgsProgramIdNMD: " + epgsProgramIdNMD + " epgsStartLongNMD: " + epgsStartLongNMD);
logFailureWriter.write("\n");
logFailureWriter.close();
System.out.println ("Match NOT found");
}
} while (epgsRecordNMD != null);
readNMD.close();
}
}
You should not make this:
if (epgsRecordXMP.equals(null)) {
break;
}
If you want to know if epgsRecordXMPis null then the if should be like this:
if (epgsRecordXMP == null) {
break;
}
To sum up: your app throws NPE when try to call equals method in epgsRecordXMP.

Error in reading a file in java

I've been trying to practice I/O file programming and I'm still at the basics. Writing into a file using the java was simple enough but reading to a file is beginning to give me a headache. Here's a simple program I tried to run(btw, I based the program from a book by Liang) .
import java.util.Scanner;
import java.io.File;
public class Reading {
private static Scanner n;
public static void main(String[] args) throws Exception
{
File files = new File("samples.txt");
n = new Scanner(files);
while(n.hasNext())
{
String firstName = n.next();
String mi = n.next();
String lastName = n.next();
int score = n.nextInt();
System.out.println(
firstName + " " + mi + " " + lastName + " " + score);
}
n.close();
}
}
Here's the error:
Exception in thread "main" java.util.NoSuchElementException
at java.util.Scanner.throwFor(Unknown Source)
at java.util.Scanner.next(Unknown Source)
at java.util.Scanner.nextInt(Unknown Source)
at java.util.Scanner.nextInt(Unknown Source)
at OOPFinals.Reading.main(Reading.java:17)
How do I make this program work?
Help!
The NoSuchElementException is thrown by Scanner.next() and means there are no more tokens to be found in the file.
The problem here is that your while() loop only guarantees that there is at least ONE token left to read from the file, however on each iteration of the loop you are reading in FIVE tokens.
What is happening in your code, you are trying to read from the Scanner although there's nothing left there to read.
What you should do - You need to check n.hasNext() before each call to n.next() or n.nextInt(), or just read the entire line (which seems exactly what you want):
while (n.hasNextLine()) {
String line = n.nextLine();
System.out.println(line);
}
Your code is working given that the right input file "samples.txt" is provided. For example, given the following input:
Richard Phillips Feynman 100
Paul Adrien Dirac 90
Everything works fine, however if you use the following:
Richard Feynman 100
Paul Adrien Dirac 90
then you obtain the NoSuchElementException. In the last example, I removed the middle name that your program is expecting. As such, we can conclude that you are expecting to read information in a file with no information left to read. I recommend something like the following:
import java.util.Scanner;
import java.util.StringTokenizer;
import java.io.File;
public class Reading {
private static Scanner n;
public static void main(String[] args) throws Exception
{
File files = new File("samples.txt");
n = new Scanner(files);
String data;
while(n.hasNextLine() && !(data = n.nextLine()).equals(""))
{
StringTokenizer st = new StringTokenizer(data);
if(st.countTokens() >= 4) {
String firstName = (String) st.nextElement();
String mi = (String) st.nextElement();
String lastName = (String) st.nextElement();
int score = Integer.parseInt( (String) st.nextElement());
System.out.println(
firstName + " " + mi + " " + lastName + " " + score);
} else {
System.err.println("This line is malformed!");
}
}
n.close();
}
}
In this program, you can have a sample file that has empty lines and it expects to read 4 tokens per line or else it prints an error message informing you that a line has malformed input.
Sometimes when you're reading a file you'll run into various characters. Some are letters, some are numbers, and some are integers. You need to check whether it's a letter, number, or an integer because the following line assumes you are passing an integer:
int score = n.nextInt();
It can be resolved by checking for integers:
int score = 0;
if(n.hasNextInt()) { score = n.nextInt(); }
When you're reading from the program, make sure to take Cathial's answer into consideration. By using hasNext(), you're only checking if there is one string, also known as a token. You should check if there are n strings available where n is the number of .next() functions in your loop.

Match simultaneous tags in Java String

I'm writing a Java program where there is some data that has to be pulled from a String (in practice this is html).
My code is as follows:
while ((line = in.readLine()) != null) {
if (line.contains("xrefInternal")) {
String ftnNum = line.replaceAll("(.*)(<sup>)([0-9]+)(</sup>)(.*)", "$3");
String ftnRefNum = line.replaceAll("(.*)(<span class=\"xrefInternal\" id=\"fo)([0-9]+)(\")(.*)", "$3");
System.out.println(ftnRefNum + "\t" + ftnNum);
}
}
While working on this I came across 2 cases in my File.
Case 1
<p class="paraNoIndent1" style="text-indent: 0%;">texy<span class="xrefInternal" id="fo249"><sup>2</sup></span> Tewxt.<span class="xrefInternal" id="fo250"><sup>3</sup></span> text</p>
Case 2
<p class="paraNoIndent1" style="text-indent: 0%;">Text.<span class="xrefInternal" id="fo248"><sup>1</sup></span></p>
Case 1 doesn't print anything. It is skipped (I think due to trying to fetch two data elements in the same paramater).
Case 2 prints the result as expected as below
248 1
Here is working Regex Fiddle
Please let me know how rework the code so that Case 1 will function like Case 2
Thanks
The behavior you describe is not a result of the regex, and cannot be reproduced with the code provided.
(I will update/delete this if/when more information is provided. It's too long for a comment, and will help the flag people.)
I get (text represents example number):
250 one 3
248 two 1
When I run this:
String example1="<p class=\"paraNoIndent1\" style=\"text-indent: 0%;\">texy<span class=\"xrefInternal\" id=\"fo249\"><sup>2</sup></span> Tewxt.<span class=\"xrefInternal\" id=\"fo250\"><sup>3</sup></span> text</p>";
String ftnNum = example1.replaceAll("(.*)(<sup>)([0-9]+)(</sup>)(.*)", "$3");
String ftnRefNum = example1.replaceAll("(.*)(<span class=\"xrefInternal\" id=\"fo)([0-9]+)(\")(.*)", "$3");
System.out.println(ftnRefNum + " one " + ftnNum);
String example2="<p class=\"paraNoIndent1\" style=\"text-indent: 0%;\">Text.<span class=\"xrefInternal\" id=\"fo248\"><sup>1</sup></span></p>";
String ftnNum2 = example2.replaceAll("(.*)(<sup>)([0-9]+)(</sup>)(.*)", "$3");
String ftnRefNum2 = example2.replaceAll("(.*)(<span class=\"xrefInternal\" id=\"fo)([0-9]+)(\")(.*)", "$3");
System.out.println(ftnRefNum2 + " two " + ftnNum2);

Manipulating Strings in a File Scanner ~ Java

I was given a file that has list of names phone numbers, calls in and out ect... Like this
Adams#Marilyn#8233331109#0#0#01012014#C
Anderson#John#5025559980#20#15#12152013#M
Baker-Brown#Angelica#9021329944#0#3#02112014#C
The # are delimiters between data items and each line has the call status as the last item.
I need to know how I can display each persons information on the screen in a format such as:
Name Phone Calls Out Calls In Last Call
Marilyn Adams (823) 333-1109 0 0 01-01-2104
John Anderson (502) 555-9980 20 15 12-15-2013
Angelica Baker-Brown (859) 254-1109 11 5 02-11-2014
I have to use substring method to extract the phone number and add parentheses/dashes ect...
So Far my code looks like this
Also I am in a beginners Java coding class....
import java.util.Scanner;
import java.io.*;
public class phonedata2_1 {
public static void main(String[] args) throws IOException {
String Phonefile, FirstName, LastName;
Scanner PhoneScan, fileScan;
System.out.println(" Name Phone Calls Out Calls In Last Call Status");
fileScan = new Scanner(new File("phonedata.txt"));
while (fileScan.hasNext()) {
Phonefile = fileScan.nextLine();
PhoneScan = new Scanner(Phonefile);
PhoneScan.useDelimiter("#");
System.out.println(PhoneScan.next() + " "
+ PhoneScan.next() + "\t"
+ PhoneScan.next() + "\t"
+ PhoneScan.next() + "\t"
+ PhoneScan.next() + "\t"
+ PhoneScan.next() + "\t"
+ PhoneScan.next());
}
System.out.println("\nTotal outgoing calls for the period: " + "\nTotal incoming calls for the period: \n");
}
}
Finds every "data-segment" by using regex, then splits it with # as delimiter and prints it:
File blub = new File("blub.txt");
Scanner scanner = null;
try
{
scanner = new Scanner(blub);
}
catch (FileNotFoundException e){}
while(scanner.hasNext("((\\S*)#){6}(\\w)"))
{
String buffer = scanner.next("((\\S*)#){6}(\\w)");
for(String value : buffer.split("#"))
System.out.print(value + " ");
System.out.println();
}
Output:
Adams Marilyn 8233331109 0 0 01012014 C
Anderson John 5025559980 20 15 12152013 M
Baker-Brown Angelica 9021329944 0 3 02112014 C
Note:
You can use any whitespace character to separate each data-segment in the input file, so even spaces are okay or tabs(or crazy mix with empty lines and so on).
For farther use of data:
you could add your data in an arraylist since buffer.split("#") gives you an array of the data-segment, so you can output it easier with your desired changes to each value.(or in a different order)
You can use the .split(String regex) to split the line you are reading by throwing in the # as a delimeter. This will yield an array which you can traverse and print the contents accordingly. Also, it would seem that besides the initial line, all call data starts with a , so you could use split twice to parse your text file:
EDIT: Seeing your comment, I also realized that afterwards, however, since the .split() method takes a regex as parameter, it means that this problem can be walked around without much hassle. My example is as follows:
String str = "Adams#Marilyn#8233331109#0#0#01012014#C Anderson#John#5025559980#20#15#12152013#M Baker-Brown#Angelica#9021329944#0#3#02112014#C";
String[] lines = str.split(" ");
System.out.println("Name\tPhone\tCalls\tOut\tCalls In\tLast Call");
for(String line : lines)
{
String[] lineInfo = line.split("#");
for(String info : lineInfo)
{
System.out.print(info + "\t");
}
System.out.println();
}
I had to add some extra tabs manually, but this is the output:
Name Phone Calls Out Calls In Last Call
Adams Marilyn 8233331109 0 0 01012014 C
Anderson John 5025559980 20 15 12152013 M
Baker-Brown Angelica 9021329944 0 3 02112014 C
Something like this should work. You still need to do all the manipulation of the phone number yourself, but all the data will be in the call info so you should be able to work from that!
while (fileScan.hasNext())
{
//Get a single record
Phonefile = fileScan.nextLine();
//Seperate the elements of the record
String[] callInfo = Phonefile.split("#");
for(String infoPart: callInfo)
{
System.out.print(infoPart+ "\t");
}
System.out.println()
}

Reading a file and displaying wanted results

I have a program that reads files like the one below.
12 9-62-1
Sample Name: 9-62-1 Injection Volume: 25.0
Vial Number: 37 Channel: ECD_1
Sample Type: unknown Wavelength: n.a.
Control Program: Anions Run Bandwidth: n.a.
Quantif. Method: Anions Method Dilution Factor: 1.0000
Recording Time: 10/2/2013 19:55 Sample Weight: 1.0000
Run Time (min): 14.00 Sample Amount: 1.0000
No. Ret.Time Peak Name Height Area Rel.Area Amount Type
min µS µS*min % mG/L
1 2.99 Fluoride 7.341 1.989 0.87 10.458 BMB
2 3.88 Chloride 425.633 108.551 47.72 671.120 BMb
3 4.54 Nitrite 397.537 115.237 50.66 403.430 bMB
4 5.39 n.a. 0.470 0.140 0.06 n.a. BMB
5 11.22 Sulfate 4.232 1.564 0.69 13.064 BMB
Total: 835.213 227.482 100.00 1098.073
From these files, the program should output a few things not everything.
The final results that I need should look like this:
0012.TXT
Sample#,Date,Time,Peak Name, Amount
9-62-1,10/2/2013,19:55,Fluoride,10.458
9-62-1,10/2/2013,19:55,Chloride,671.120
9-62-1,10/2/2013,19:55,Nitrite,403.430
9-62-1,10/2/2013,19:55,Sulfate,13.064
But, right now they look like this:
0012.TXT
Sample#,Date,Time,Peak Name, Amount
9-62-1,10/2/2013,19:55,Fluoride,10.458 ,
Chloride,671.120 ,
Nitrite,403.430 ,
n.a.,n.a.,
Sulfate,13.064 ,
,1098.073 ,
Here is my code and what I have done.
Scanner input = new Scanner(new FileReader(selectFile.getSelectedFile()));
System.out.println("Sample#,Date,Time,Peak Name,Amount");
int linesToSkip = 28;
BufferedReader br = new BufferedReader(new FileReader(selectFile.getSelectedFile()));
String line;
while ( (line = br.readLine()) != null) {
if (linesToSkip-- > 0) {
continue;
}
if (line.contains("n.a.")) {
continue;
}
if (line.contains("Total")) {
continue;
}
String[] values = line.split("\t");
int index = 0;
for (String value : values) {
/*System.out.println("values[" + index + "] = " + value);*/
index++;
}
while (input.hasNext()) {
String word = input.next();
Pattern pattern1 = Pattern.compile("Name:");
Pattern pattern2 = Pattern.compile("Time:");
Matcher matcher1 = pattern1.matcher(word);
Matcher matcher2 = pattern2.matcher(word);
Matcher matcher3 = pattern2.matcher(word);
if(matcher1.matches()){
System.out.print(input.next() + ",");
}
if(matcher2.matches()){
System.out.print(input.next() + ",");
}
if(matcher3.matches()){
System.out.print(input.next() + ",");
}
System.out.print("");
}
System.out.print(values[2]+",");
System.out.println(values[6]+"\b,");
}
br.close();
How can I make the output look like these with the sample#, Date and Time then followed by the peak name and amount and print them that way on each line?
Sample#,Date,Time,Peak Name, Amount
9-62-1,10/2/2013,19:55,Fluoride,10.458
9-62-1,10/2/2013,19:55,Chloride,671.120
9-62-1,10/2/2013,19:55,Nitrite,403.430
9-62-1,10/2/2013,19:55,Sulfate,13.064
Thanks!
Something like:
while ( (line = br.readLine()) != null) {
if (line.contains("n.a.")) {
continue;
}
//Your code
You can do the same in your inner while loop for specific table item for peak name value and the amount value. In that case you can use String#equales() method.
Edit for Comments:
You are over complicating your things while printing and reading your file content. Dont use Scanner as well as BufferedReader. One will do the work for you.
You have very specific format for your file. You really dont need to use regex for this purpose, which you are using in your inner while loop.
For sample name to match use String#equales() method and do you operations accordingly.
Get the values you needed from upper section of your file like Sample Name and Recording Time, keep them handy, so that you could use them later.
From you lower section get Peak Name and amount from each row.
While printing construct your String by making use of these collected values.
Another Edit for Comments:
the following code is not tested, so there could be some issues, but you can figure them out.
If you look at String Class then you will find many useful methods.
BufferedReader br = new BufferedReader(new FileReader(selectFile.getSelectedFile()));
String recTime, peakName, amount, sample ;
int linesToSkip = 28;
String line = br.readLine();
if(line != null){
String[] values = line.split("\t");
sample = values[1];
}
while ( (line = br.readLine()) != null) {
values = line.split("\t");
if (line.startsWith("Sample Name")) {
// Check here value[1] is equal to sample. If this is needed.
// You got your sample name here
} else if (line.startsWith("Recording Time")) {
recTime = values[1];
// You got your Recording Time here
} else if(values.length > 4 ){
// get Peak Name and recording time
peakName = values[2];
amount = values[6];
} else if (line.contains("n.a.") || line.contains("Total") || linesToSkip-- > 0) {
/* may not needed linesToSkip-- > 0 in above condition */
continue;
}
System.out.println(sample +" ," + recTime + " ," + peakName + " ," + amount);
}
I hope this helps. Good Luck.

Categories