Reading a space-delimited text file with blanks - java

I'm trying to read a text file which has tab space as delimiter but some values are left blank in it, how do i identify that value is left blank while reading the file. Please check my code below
FileReader file = new FileReader(new File("File.dat"));
BufferedReader br = new BufferedReader(file);
String temp = br.readLine();
while (temp != null) {
temp = br.readLine();
System.out.println(temp);
}
Please help me in pointing out the values that are left blank.

This looks like a CSV file, but instead of commas, are tabs. You can use opencsv for read the file.
CSVReader reader = new CSVReader(new FileReader("file.txt"), '\t');
String [] nextLine;
while ((nextLine = reader.readNext()) != null) {
// nextLine[] is an array of values from the line
System.out.println(nextLine[0] + nextLine[1] + "etc...");
}
The columns with blank value as empty strings in the array.
Or more simple:
CSVReader reader = new CSVReader(new FileReader("file.txt"), '\t');
List<String[]> all = reader.readAll();

Using #HunterMcMillen hint:
FileReader file = new FileReader(new File("File.dat"));
BufferedReader br = new BufferedReader(file);
String temp = br.readLine();
while (temp != null) {
String[] tabSeparatedArray = temp.split("\t")
foreach(String tabElement : tabSeparatedArray){
if (tabElement.trim().length <= 0){
//here the element is blank... do whatever you want!!!!
}
}
System.out.println(temp);
temp = br.readLine();
}

Related

How to read text file without the headline into ArrayList

I'm currently working on an assignment and I cannot find any clue to remove the headline from the text file and write the rest into an ArrayList. Can someone help me?
ID,Nama,GajiPokok,JmlAbsensi,JmlIzin
2,Peter,5000000,17,3
1,John,4500000,19,1
3,Linda,10000000,13,7
4,Lucy,7000000,20,0
Here is my code:
BufferedReader in = new BufferedReader(new FileReader("D:\\" + args[0] + ".txt"));
try {
String line = in.readLine();
String data[];
while (line != null){
data = line.split(",");
Staff s = new Staff(){};
s.setID(Integer.parseInt(data[0]));
s.setNama(data[1]);
s.setGajiPokok(Long.parseLong(data[2]));
s.setjmlhAbsensi(Integer.parseInt(data[3]));
s.setjmlhIzin(Integer.parseInt(data[4]));
s.getID();
s.getNama();
s.getGajiPokok();
s.getjmlhAbsensi();
s.getjmlhIzin();
list_Staff.addAll(Arrays.asList(s));
line = in.readLine();
}
in.close();
} catch (IOException e){e.printStackTrace();}
If you want to ignore first line while reading the CSV file then you can simple skip processing of 1st line by calling in.readLine(); twice at the start as shown in below example:
BufferedReader in = new BufferedReader(new FileReader("D:\\" + args[0] + ".txt"));
String line = in.readLine();
line = in.readLine(); //skip fist line and read second line
String data[];
while (line != null){
data = line.split(",");
Staff s = new Staff(){};
s.setID(Integer.parseInt(data[0]));
s.setNama(data[1]);
s.setGajiPokok(Long.parseLong(data[2]));
s.setjmlhAbsensi(Integer.parseInt(data[3]));
s.setjmlhIzin(Integer.parseInt(data[4]));
s.getID();
s.getNama();
s.getGajiPokok();
s.getjmlhAbsensi();
s.getjmlhIzin();
list_Staff.addAll(Arrays.asList(s));
line = in.readLine();
}
Using skip() method of JAVA 8 Streams:
try(BufferedReader in = new BufferedReader(new FileReader("D:\\" + args[0] + ".txt"))) {
Stream<String> lines = in.lines();
List<Staff> staff = lines.skip(1).map(line -> {
Staff s = new Staff();
String data[] = line.split(",");
s.setID(Integer.parseInt(data[0]));
s.setNama(data[1]);
s.setGajiPokok(Long.parseLong(data[2]));
s.setJmlhAbsensi(Integer.parseInt(data[3]));
s.setJmlhIzin(Integer.parseInt(data[4]));
return s;
}).collect(Collectors.toList());
System.out.println(staff);
}
You can declare the following line twice or initialize integer variable and skip the loop if its zero.
String line = in.readLine();
This solution works.
private void readTextFile(String fileName) throws FileNotFoundException {
BufferedReader in = new BufferedReader(new FileReader(fileName));
Stream<String> stream = in.lines();
List<String> answer = stream.collect(Collectors.toList());
// For Pre-Java8
/*for (int i = 1; i < answer.size(); i++) {
System.out.println(answer.get(i));
}*/
// Split afterwards.
Stream<String> ans = answer.stream().filter(p -> !p.equals(answer.get(0)));
ans.forEach(x -> System.out.println(x));
}

Randomly read text from specific column in a file using Java

I would like to randomly select single name from column1 between Robert,Shawn,John.
Example The File has following names
Robert,Brian
Shawn,Bay
John,Paul
Any Help would be highly appreciated
FileInputStream objfile = new FileInputStream(System.getProperty("user.dir")+path);
in = new BufferedReader(new InputStreamReader(objfile ));
String line = in.readLine();
while (line != null && !line.trim().isEmpty()) {
String eachRecord[]=line.trim().split(",");
Random rand = new Random();
//trying to randomly select text from specific row in a property file
sendKeys(firstName,rand.nextInt((eachRecord[0]));
line = in.readLine();
}
}
This gets a random name from column 1 into the variable randomName:
final int column = 1;
final String path = "file.ext";
Random rand = new Random();
List<String> lines = Files.readAllLines(Paths.get(path), StandardCharsets.UTF_8);
String randomName = lines.get(rand.nextInt(lines.size())).split(",")[column - 1];
FileReader fr = new FileReader(path_of_your_file);
BufferedReader br = new BufferedReader(fr);
String sCurrentLine;
ArrayList<String> nameList=new ArrayList<String>(); //keep each first column entry inside this list.
while ((sCurrentLine = br.readLine()) != null) {
StringTokenizer st=new StringTokenizer(sCurrentLine, ",");
String name=st.nextToken();
nameList.add(name);
}
System.out.println(nameList.get((int)(Math.random()*nameList.size())));
//close file resources at finally block.

Read from csv file with split missing in Java

I want to read csv file with BufferedReader and split with StringTokenizer. However there is one line in file which contains this line :
ide,12,office,,3208.83,0.18,577.5,4876
Also here is my read method;
public void readFromCSV(){
try {
File file = new File(myFile);
br = new BufferedReader(new FileReader(file));
String line = null;
while((line = br.readLine()) != null) {
st1 = new StringTokenizer(line,"\n");
while(st1.hasMoreTokens()) {
oneLineList = new ArrayList<>();
st2 = new StringTokenizer(st1.nextToken(),",");
for(int i = 0; i < 8; i++) {
oneLineList.add(st2.nextToken());
}
dataList.add(counter,oneLineList);
}
counter++;
}
br.close();
}catch(IOException ex) {
ex.printStackTrace();
}
}
In for statement, there are 8 fields in each line, and dataList is a two-dimensional array list.
I cannot read whole data because of one line contain consecutive coma, how should I do for fix this?

extracting particular text from a huge file in java

I have files containing text in pattern like this
Type:status
Origin:some text
Text:some text
URL:some url
Time:time
around 500 lines with same pattern. I want to extract only the text part from it. I tried reading the file with BufferedReader and used indexOf("Text") and indexOf("URL") and subString(i,j) but its giving exception at run time. How can I do this. My code:
FileReader fr = new FileReader("test.txt");
BufferedReader br = new BufferedReader(fr);
FileWriter wr = new FileWriter("new.txt");
// char buffer[] = null;
String s;
String str="";
BufferedWriter bw = new BufferedWriter(wr);
while ((s = br.readLine()) != null) {
str= str + s;
i = str.indexOf("Text:");
j= str.indexOf("URL:");
String a= str.substring(i, j);
bw.write(a);
}
br.close();
bw.close();
The "Text:" is found first in the 3rd line and "URL:" in the 4th, but if your program doesn't find both strings, it throws an exception.
Even if it worked you would find the same text over and over again.
Try something like this:
FileReader fr = new FileReader("test.txt");
BufferedReader br = new BufferedReader(fr);
FileWriter wr = new FileWriter("new.txt");
String s;
BufferedWriter bw = new BufferedWriter(wr);
while ((s = br.readLine()) != null) {
if (s.startsWith("Text:"))
bw.write(s);
}
br.close();
bw.close();
You could use
String[] pieces = str.split(":");
That will give you an array of strings split by what ever you put in the parenthesis. Then if you know the pattern you can get each piece out by iterating through it in a loop. For example: if you know that Type is at [0] and six things in each sequence you can say that the next Type will be at [6] and so on.
You should check for indexes. Of i and j. If one line is wrong, it will skip it and print the line that is wrong to the console. You should probably handle it in a different way but keep in mind that substring shouldn't love indexes of -1.
FileReader fr = new FileReader("test.txt");
BufferedReader br = new BufferedReader(fr);
String tokenText = "Text:";
String tokenURL = "URL:";
FileWriter wr = new FileWriter("new.txt");
// char buffer[] = null;
String s;
String str="";
BufferedWriter bw = new BufferedWriter(wr);
while ((s = br.readLine()) != null) {
String a;
str = str + s;
i = str.indexOf(tokenText);
j = str.indexOf(tokenURL);
if (i < 0 && j >= 0){
// pad with the token string
a = s.substring(j + tokenURL.length);
} else if(i >= 0) {
// pad with the token string
a = s.substring(i + tokenText.length);
} else {
System.out.printl("Unparsed line:");
System.out.printl(s);
}
bw.write(a);
}
br.close();
bw.close();
That said, as jonhchen902 said in the comments, you could also check for the strings after the while loop. It really depends on your input file and if you're expecting to find the "string" multiple times or once.
According to your example, Text: and Url: are on consecutive lines.
Your problem is you're reading the file line by line (br.readLine()), so calling indexOf() will most of the time return -1 in i or j (and you will never find both strings, since they aren't on the same line).
As the javadoc of substring() states, calling the method with a negative start index will throw an IndexOutOfBoundsException. So your approach isn't right.
You should instead parse the file line by line as you're doing, and simply test for a positive index to the call to indexOf("Text:"), and then substring the current line starting at the returned index + 5.
Not tested:
while ((line = br.readLine()) != null) {
i = line.indexOf("Text:");
if (i > 0) {
String text = line.substring(i);
bw.write(text + "\n");
}
}

Write values from multidimensional array to csv file in java

I wrote a small Java program that reads the data from CSV file and I have to save these values in 2 dimensional array. Now I need to write these values (not all information will be stored because the array contains many redundant data) from this array to a new CSV file. Can anyone help me with a code sample, I searched a lot but could not find an answer. My code is:
int row = 0;
int col = 0;
String[][] numbers=new String[24][24];
File file = new File("D:\\thesis\\sorted_file.csv");
if(file.exists())
{
System.out.println("file exist");
}
BufferedReader bufRdr;
bufRdr = new BufferedReader(new FileReader(file));
String line = null;
String delims=",";
//read each line of text file
while((line = bufRdr.readLine()) != null )
{
StringTokenizer st = new StringTokenizer(line,delims);
col=0;
while (st.hasMoreTokens())
{
//get next token and store it in the array
numbers[row][col] = st.nextToken();
System.out.print("number["+row+"]["+col+"]:"+numbers[row][col]);
col++;
}
row++;
}
You can use something like this...
BufferedWriter br = new BufferedWriter(new FileWriter("myfile.csv"));
StringBuilder sb = new StringBuilder();
for (String element : numbers) {
sb.append(element);
sb.append(",");
}
br.write(sb.toString);
br.close();

Categories

Resources