Reading .tsv file in Java - java

I am a beginner and I am trying to read a .tsv data in Java and save the lines to an ArrayList. I wrote a method for it but the only thing I get is line id's and nothing more... I can't find an error. Could you please help me?
public static ArrayList<String[]> tsvr(File test2) throws IOException {
BufferedReader TSVReader = new BufferedReader(new FileReader(test2));
String line = TSVReader.readLine();
ArrayList<String[]> Data = new ArrayList<>(); //initializing a new ArrayList out of String[]'s
try {
while (line != null) {
String[] lineItems = line.split("\n"); //splitting the line and adding its items in String[]
Data.add(lineItems); //adding the splitted line array to the ArrayList
line = TSVReader.readLine();
} TSVReader.close();
} catch (Exception e) {
System.out.println("Something went wrong");
}
return Data;
}

First, you should move readLine to a while, so that you can read all the lines of the file. Then you should split the line by tab \t because it is a tab separated file
public static ArrayList<String[]> tsvr(File test2) {
ArrayList<String[]> Data = new ArrayList<>(); //initializing a new ArrayList out of String[]'s
try (BufferedReader TSVReader = new BufferedReader(new FileReader(test2))) {
String line = null;
while ((line = TSVReader.readLine()) != null) {
String[] lineItems = line.split("\t"); //splitting the line and adding its items in String[]
Data.add(lineItems); //adding the splitted line array to the ArrayList
}
} catch (Exception e) {
System.out.println("Something went wrong");
}
return Data;
}
If you want to print the list of array:
Data.forEach(array -> System.out.println(Arrays.toString(array)));

Explanation
You have to split on \t (tab) instead of \n (newline). As your lines are already single lines, not multiple.
Another issue in your code is that you close your stream manually, this is unsafe and will create a resource leak in exception-case. You may use try-with-resources to close it safely.
NIO
Instead of fixing your existing code which other answers already did, may I suggest a more compact and possibly more readable version that uses NIO (Java 8 or newer) which does the same:
return Files.lines(file.toPath())
.map(line -> line.split("\t"))
.collect(Collectors.toList());
If you can modernize your method parameters, I would suggest to make it Path path instead of File file, then you can simply do Files.lines(path)

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 textfile line by line and put in object array

I have to make an EPG app using java, but I am kind of new in programming and it's due tomorrow and it's still not working properly.
I have a question about a small part: I have to read the programs from a text file. Each line contains multiple things, the channel, the title of the program, a subtitle, a category, etcetera.
I have to make sure that I can read the separate parts of each line, but it's not really working, it's only printing the parts from the first line.
I am trying, but I can't find why it's not printing all the parts from all the lines in stead of printing only the parts from the first line. Here's the code:
BufferedReader reader = new BufferedReader(newFileReader(filepath));
while (true) {
String line = reader.readLine();
if (line == null) {
break;
}
}
String[] parts = line.split("\\|", -1);
for(int i = 0; i < parts.length; i++) {
System.out.println(parts[i]);
}
reader.close();
Does anybody know how to get all the lines in stead of only the first?
Thank you!
readLine() only reads one line, so you need to loop it, as you said.
BUT with reading to the String inside of the while loop you always overwrite that String.
You would need to declare the String above the while loop that you can access it from outside, too.
BTW, it seems that your braces for the if don't match.
Anyway, I'd fill the information into an ArrayList, look below:
List<String> list = new ArrayList<>();
String content;
// readLine() and close() may throw errors, so they require you to catch it…
try {
while ((content = reader.readLine()) != null) {
list.add(content);
}
reader.close();
} catch (IOException e) {
// This just prints the error log to the console if something goes wrong
e.printStackTrace();
}
// Now proceed with your list, e.g. retrieve first item and split
String[] parts = list.get(0).split("\\|", -1);
// You can simplify the for loop like this,
// you call this for each:
for (String s : parts) {
System.out.println(s);
}
Use apache commons lib
File file = new File("test.txt");
List<String> lines = FileUtils.readLines(file);
As ArrayList is Dynamic,try,
private static List<String> readFile(String filepath) {
String line = null;
List<String> list = new ArrayList<String>();
try {
BufferedReader reader = new BufferedReader(new FileReader(filepath));
while((line = reader.readLine()) != null){
list.add(line);
}
} catch (Exception e) {
e.printStackTrace();
}
return list;
}

Read text containing multiple line using bufferedreader

I would like to know how to read a text file containing multiple lines in java using BufferedStreamReader.
Every line has two words separated by (;) and I want to use split() String operation to separate the 2 words. I also need to compare each word to a word in a master arraylist.
I'm having problems to continue.
Here's my code:
{
FileInputStreamReader f = new FileInputStreamReader(C://Desktop/test.txt);
InputStreamReader reader = new InputStreamReader(f);
BufferedReader Buff = new BufferedReader (reader);
String Line = buff.readLine();
String t[] = Line.split(;);
}
Replace
String Line = Buff.readLine();
with
// buffer for storing file contents in memory
StringBuffer stringBuffer = new StringBuffer("");
// for reading one line
String line = null;
// keep reading till readLine returns null
while ((line = Buff.readLine()) != null) {
// keep appending last line read to buffer
stringBuffer.append(line);
}
Now, you have read the complete file into StringBuffer, you do whatever you want.
Hope this helps.
Try
while((line=buff.readLine())!=null){
System.out.println(line);
}
You need a while loop to read all the lines.
Here is an example http://www.mkyong.com/java/how-to-read-file-from-java-bufferedreader-example/
You can use BufferedReader to loop through each of the line encountered within the specified file. In order to get your words split by a ";", you can use .split and can store the resulting array in a list.
Finally, combine all the lists to a single list which would inturn hold all the words present in your file.
List<String> words = Arrays.asList(line.split(";"));
list.addAll(words);
Now you would want to compare the retrieved list against a Master list containing all your records.
// Compare the 2 lists, assuming your file list has less number of
// records
masterList.removeAll(list);
The above statement can be used in reverse too; in case the file holds the master list of words. Alternatively, you can store the 2 lists in temporary lists and compare in whatsoever way your require.
Here is the complete code:
public static void main(String[] args) {
String line;
// List of all the words read from the file
List<String> list = new ArrayList<String>();
// Your original mast list of words against which you want to compare
List<String> masterList = new ArrayList<String>(Arrays.asList("cleaner",
"code", "java", "read", "write", "market", "python", "snake",
"stack", "overflow"));
BufferedReader reader;
try {
reader = new BufferedReader(new FileReader("testing.txt"));
while ((line = reader.readLine()) != null) {
// Add all the words split by a ; to the list
List<String> words = Arrays.asList(line.split(";"));
list.addAll(words);
}
// Compare the 2 lists, assuming your file list has less number of
// records
masterList.removeAll(list);
System.out.println(masterList);
reader.close();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
File which I have created looks like:
cleaner;code
java;read
write;market
python;snake
The output of the above code:
[stack, overflow]

Android reading file from assets and storing in array list

My app needs to read from several files in the assets folder. But my file has delimiters $$$ and ||. The structure of the file is like this.
Construction$$$
All the work involved in assembling resources and
putting together the materials required to form a new or changed
facility.||
Construction Contractor$$$
A corporation or individual
who has entered into a contract with the organization to perform
construction work.||
The sentences ending with $$$ are to be stored in seperate array list and the sentences ending with || are to be stored on seperate array list.
How can i do this? Any sample or example code will be appreciated. Note that these files are very long.
BufferedReader br = null;
try {
br = new BufferedReader(new InputStreamReader(getAssets().open("c.txt"))); //throwing a FileNotFoundException?
String word;
while((word=br.readLine()) != null)
A_Words_array.add(word); //break txt file into different words, add to wordList
}
catch(IOException e) {
e.printStackTrace();
}
finally {
try {
br.close(); //stop reading
}
catch(IOException ex) {
ex.printStackTrace();
}
}
String[]words = new String[A_Words_array.size()];
A_Words_array.toArray(words); //make array of wordList
for(int i=0;i<words.length; i++)
Log.i("Read this: ", words[i]);
Above is the code i found now how to split my sentences based upon ending delimiters?
Asuming that each sentence is in one line and they finish either with $$$ or ||, you can store the lines in different arrays depending on its endings:
List<String> list1 = new ArrayList<>();
List<String> list2 = new ArrayList<>();
String line;
while (line = br.readLine()) != null) {
if (line.endsWith("$$$")) {
list1.add(line);
} else {
list2.add(line);
}
}
String[] dollarlines = list1.toArray(new String[list1.size()]);
String[] verticalLines = list2.toArray(new String[list2.size()]);

In Java, I want to split an array into smaller arrays, the length of which varys with inputted text files

So far, I have 2 arrays: one with stock codes and one with a list of file names. What I want to do is input the .txt files from each of the file names from the second array and then split this input into: 1. Arrays for each file 2. Arrays for each part with each file.
I have this:
ImportFiles f1 = new ImportFiles("File");
for (String file : FileArray.filearray) {
if (debug) {
System.out.println(file);
}
try {
String line;
String fileext = "C:\\ASCIIpdbSKJ\\"+file+".txt";
importstart = new BufferedReader(new FileReader(fileext));
for (line = importstart.readLine(); line != null; line = importstart.readLine()) {
importarray.add (line);
if (debug){
System.out.println(importarray.size());
}
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
importarray.add ("End")
This approach works to create a large array of all the files, will it be easier to change the input method to split it as it is coming in or split the large array I have?
At this point, the stock code array is irrelevant. Once I have split the arrays down I know where I will go from there.
Thanks.
Edit: I am aware that this code is incomplete in terms of { } but it is only printstreams and debugging missed off.
If you want to get a map with a filename and all its lines from all the files, here are relevant code parts:
Map<String, List<String>> fileLines = new HashMap<String, List<String>>();
for (String file : FileArray.filearray)
BufferedReader reader = new BufferedReader(new FileReader(fileext));
List<String> lines = new ArrayList<String>();
while ((line = reader.readLine()) != null){
lines.add(line);
}
fileLines.put(file, lines);
}

Categories

Resources