Why this code skip the first line of file? [duplicate] - java

This question already has answers here:
Reading UTF-8 - BOM marker
(9 answers)
Closed 5 years ago.
I applied this code more than one, this code is to read a file and for each line, it should create a new object and add it to att_agreement ArrayList, it works fine for each line except the first line, I can not find its object in the output.
Any help, please?
public ArrayList<Att_Elements> load_ann(File f) {
ArrayList<Att_Elements> att_agreement = new ArrayList<Att_Elements>();
String line="";
try {
BufferedReader read = new BufferedReader(new InputStreamReader(new FileInputStream(f), "UTF8"));
while((line = read.readLine()) != null) {
String[] SplitLine = line.split("\\|");
if (SplitLine[0].equals("Att")) {
annotation=new Att_Elements();
annotation.Type = SplitLine[0];
.
.
.
//...
att_agreement.add(annotation);
}
}
read.close();
} catch (IOException e) {
e.printStackTrace();
}
return att_agreement;
}
Here is a sample of file content (3 lines):

Your file likely has what is called a BOM located at the beginning. This is a byte order mark. Thus, your conditional .equals("Att") is not being met until the second line where the BOM is not present. A separate if statement to handle this case should work well. If you print each line read, you should see what the BufferedReader is reading as the first line. The new conditional statement can then be tailored to this value.
Another approach is to search for a generic BOM string and replace it with nothing.

Related

split method to output values under each other when reading from a file

My code works fine however it prints the values side by side instead of under each other line by line. Like this:
iatadult,DDD,
iatfirst,AAA,BBB,CCC
I have done a diligent search on stackoverflow and none of my solution's seem to work. I know that I have to make the change while the looping is going on. However none of the examples I have seen have worked. Any further understanding or techniques to achieve my goal would be helpful. Whatever I am missing is probably very small. Please help.
String folderPath1 = "C:\\PayrollSync\\client\\client_orginal.txt";
File file = new File (folderPath1);
ArrayList<String> fileContents = new ArrayList<>(); // holds all matching client names in array
try {
BufferedReader reader = new BufferedReader(new FileReader(file));// reads entire file
String line;
while (( line = reader.readLine()) != null) {
if(line.contains("fooa")||line.contains("foob")){
fileContents.add(line);
}
//---------------------------------------
}
reader.close();// close reader
} catch (Exception e) {
System.out.println(e.getMessage());
}
System.out.println(fileContents);
Add a Line Feed before you add to fileContents.
fileContents.add(line+"\n");
By printing the list directly as you are doing you are invoking the method toString() overridden for the list which prints the contents like this:
obj1.toString(),obj2.toString() .. , objN.toString()
in your case the obj* are of type String and the toString() override for it returns the string itself. That's why you are seeing all the strings separated by comma.
To do something different, i.e: printing each object in a separate line you should implement it yourself, and you can simply append the new line character('\n') after each string.
Possible solution in java 8:
String result = fileContents.stream().collect(Collectors.joining('\n'));
System.out.println(result);
A platform-independent way to add a new line:
fileContents.add(line + System.lineSeparator);
Below is my full answer. Thanks for your help stackoverflow. It took me all day but I have a full solution.
File file = new File (folderPath1);
ArrayList<String> fileContents = new ArrayList<>(); // holds all matching client names in array
try {
BufferedReader reader = new BufferedReader(new FileReader(file));// reads entire file
String line;
while (( line = reader.readLine()) != null) {
String [] names ={"iatdaily","iatrapala","iatfirst","wpolkrate","iatjohnson","iatvaleant"};
if (Stream.of(names).anyMatch(line.trim()::contains)) {
System.out.println(line);
fileContents.add(line + "\n");
}
}
System.out.println("---------------");
reader.close();// close reader
} catch (Exception e) {
System.out.println(e.getMessage());
}

Reading files with use of Delimiter in Java [duplicate]

This question already has answers here:
How do I split a string in Java?
(39 answers)
Closed 5 years ago.
I am trying to read text file with 3 lines:
10
PA/123#PV/573#Au/927#DT/948#HY/719#ZR/741#bT/467#LR/499#Xk/853#kD/976#
15.23#25.0#17.82#95.99#23.65#156.99#72.85#62.99#112.0#55.99#
So far in my main method I have:
`String fileName = "productData.txt";
String line = null;
try {
FileReader fileReader = new FileReader(fileName);
BufferedReader bufferedReader =
new BufferedReader(fileReader);
while((line = bufferedReader.readLine()) != null) {
System.out.println(line);
}
bufferedReader.close();
}
catch(FileNotFoundException e) {
System.out.println(e);
}
catch(IOException e) {
e.printStackTrace();
}`
But Im not sure how I would go on with using the String DELIMITER = "#";
In the text file Line 1: is applied to number of types of product, Line 2: are product codes separated by #, and in Line 3: Price per unit of the corresponding products separated by #.
So Im looking for kind of format PA/123 Costs 15.23. How would I do that?
You can you line.split('#'); to get an array of Strings. This array contains your 10 elements.
Then you have two arrays of size 10. So firstArray[0] contains the name of the first product and secondArray[0] contains the price of it.

How to read data from file till I encounter an empty line [duplicate]

This question already has answers here:
How can I read a large text file line by line using Java?
(22 answers)
Closed 6 years ago.
Is there a way I can read multiple lines from a text file until I encounter an empty line?
For example my text file looks like this:
text-text-text-text-text-text-text-text-text-text-text-text-text-text-text-text
//This is empty line
text2-tex2-text2-tex2-text2-tex2-text2-text2
Now, I want to input text-text... till the empty line into a string. How can I do that?
check below code, 1st i have read all the lines from text file, then i have check whether file contains any blank line or not, if it contains then i break the loop.
A.text
text-text-text-text-text-text-text-text-text-text-text-text-text-text-text-text
text2-tex2-text2-tex2-text2-tex2-text2-text2
import java.util.*;
import java.io.*;
public class Test {
public static void main(String args[]){
try (BufferedReader br = new BufferedReader(new FileReader("E:\\A.txt"))) {
String line;
while ((line = br.readLine()) != null) {
if(!line.isEmpty()){
System.out.println(line);
} else {
break;
}
}
} catch(Exception e) {
e.printStackTrace();
}
}
}

Parsing text Java from PDF [duplicate]

This question already has answers here:
Advanced PDF parser for Java
(5 answers)
Closed 7 years ago.
I would like to ask, how can i parse text. I had extracted text from PDF file with PDFBox into normal text, which is output in console. For example this one:
SHA256: 51c11994540537b633cf91b276b3c34556695ed870a5d3f7451e993262a4a745
File name: ACleaner.zip
Detection ratio: 0 / 55
Analysis date: 2015­07­21 12:23:19 UTC ( 8 minutes ago )
0 0
? Analysis ? File detail ? Additional information ? Comments  0 ? Votes
MD5  fffa183f43766ed39d411cb5f48dbc87
SHA1  b0d40fbc6c722d59031bb488455f89ba086eacd9
SHA256  51c11994540537b633cf91b276b3c34556695ed870a5d3f7451e993262a4a745
I need to get some values, for example value of MD5, File name etc..how can i reach it in Java? Thanks a lot
I have tried so : in this while a i added this
String keySHA256 = "SHA256:";
private static String SHA256Value = null;
if (line.contains(keySHA256)) {
// System.out.println(line);
int length = keySHA256.length();
SHA256Value = line.substring(length);
System.out.println("SHA256 >>>>" + SHA256Value);
}
but sometimes it doesnt get right value..please help..
This could be a good example for you to start learning more about Java IO and String parsing. Google is your friend.
//uri where your file is
String fileName = "c://lines.txt";
// read the file into a buffered reader
try (BufferedReader br = new BufferedReader(new FileReader(fileName))) {
String line;
while ((line = br.readLine()) != null) { //iterate on each line of the file
System.out.println(line); // print it if you want
String[] split=line.split(" "); // split your line into array of strings, each one is a separate word that has no spaces in it.
//add any checks or extra processes here
}
} catch (IOException e) {
e.printStackTrace();
}

read lines in txt file [java] [duplicate]

This question already has answers here:
Java: Reading a file into an array
(5 answers)
Closed 1 year ago.
I'll try to be as clear as possible but pardon me if my question is not perfect.
I have a txt file with several lines of data. example:
123 ralph bose 20000 200 1 2
256 ed shane 30000 100 2 4
...
I need to read each line sequentially and pass it back to a method in a separate class for processing. I know how to break down each line into elements by using StringTokenizer.
However, i'm not sure how to read one line at a time, pass back the elements to the other class and then, once the processing is done, to read the NEXT line. Method cooperation between my classes works fine (tested) but how do i read one line at a time?
I was thinking of creating an array where each line would be an array element but as the number of lines will be unknown i cannot create an array as i don't know its final length.
Thanks
Baba
EDIT
rough setup :
Class A
end_of_file = f1.readRecord(emp);
if(!end_of_file)
{
slip.printPay(slipWrite);
}
Class B
public boolean readRecord(Employee pers) throws IOException {
boolean eof = false ;
String line = in.readLine() ;
???
}
filename is never passed around
so up until here i can read the first line but i think i need a way to loop through the lines to read them one by one with back and forth between classes.
tricky...
There are lots of ways to read an entire line at a time; Scanner is probably easiest:
final Scanner s = new Scanner(yourFile);
while(s.hasNextLine()) {
final String line = s.nextLine();
YourClass.processLine(line);
}
void readLine(String fileName)
{
java.io.BufferedReader br = null;
try
{
br = new java.io.BufferedReader(new java.io.FileReader(fileName));
String line = null;
while(true)
{
line = br.readLine();
if(line == null)
break;
// process your line here
}
}catch(Exception e){
}finally{
if(br != null)
{
try{br.close();}catch(Exception e){}
}
}
}
Also if you want to split strings... use
String classes split method. for splitting depending on space... you can do ... line.split("\\s*")
Hope it works

Categories

Resources