To print the given rows of string into columns - java

I have *.txt file with first row as name,address,mail id and second line with the values. I have to print this into two columns,the first one with the headings and second with the value using Java. how do I do this?
public class ReadFile1 {
public static void main(String[] args) {
BufferedReader br=null;
String sCurrentLine = null;
String delimiter = ",";
String[] filetags;
try {
br = new BufferedReader(new FileReader("path\\Read.txt"));
sCurrentLine = br.readLine();
StringBuffer result = new StringBuffer();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
String line = null;
try {
line = br.readLine();
} catch (IOException e) {
e.printStackTrace();
}
filetags = line.split(delimiter);
for(int i = 0;i < line.length(); i++)
{
System.out.println("****" +sCurrentLine);
String[] s = line.split(",");
for(int j = i-1; j<line.length();j++)
{
System.out.println("##############"+Arrays.toString(s));
}
}
}
}
This is what I tried. Ex: I have a file say,
line1) name,email,mobile and second
line2) john,j#abc.com,9876
line3) max,max#xyz.com,1234
Now, I need to print:
name john
email john#abc.com
moblie 9876
name max
email max#xyz.com
mobile 1234

Below is one way you may be able to get what you want, It is similar to how you have attempted but slightly more refined.
The File:
name,email,mobile and second
john,j#abc.com,9876
max,max#xyz.com,1234
The code:
//File is on my Desktop
Path myFile = Paths.get(System.getProperty("user.home")).resolve("Desktop").resolve("tester.txt");
//Try-With-Resources so we autoclose the reader after try block
try(BufferedReader reader = new BufferedReader(new FileReader(myFile.toFile()))){
String[] headings = reader.readLine().split(",");//Reads First line and gets headings
String line;
while((line = reader.readLine()) != null){//While there are more lines
String[] values = line.split(","); //Get the values
for(int i = 0; i < values.length; i++){//For each value
System.out.println(headings[i] + ": " + values[i]);//Print with a heading
}
}
} catch (IOException io) {
io.printStackTrace();
}
Good Luck!

Something like this should do the trick.
Read the file and store each line in a list.
Iterate through the list of lines
If it is safe to assume the first line will always be the title line, take the input and store it in a collection.
For the rest of the lines, split on the comma and use the index of the splitter array to refer to the title column.
List <String> lines = new ArrayList<String>();
Scanner scanner = new Scanner(new File("FileName.txt"));
while(scanner.hasNextLine()){
String line = scanner.nextLine();
lines.add(line);
}
scanner.close();
int lineNo = 0;
List <String> title = new ArrayList<String>();
for(String line : lines){
if(lineNo == 0){
String [] titles = line.split(",");
for(String t : titles){
title.add(t);
}
lineNo++;
}
else{
String input = line.split(",");
for(int i = 0; i<input.length; i++){
System.out.println(title.get(i) + ": " + input[i]);
}
lineNo++;
}
}

Related

How to get text from a TextFile and putting it to a Table

I am trying to put text from a text file to a table I want it to display on the table when pressing a button. It does not display any errors it just does not work. Can someone please explain why and how to make it work. The text is divided with ;
private void jButton4ActionPerformed(java.awt.event.ActionEvent evt)
{
try {
BufferedReader br = new BufferedReader(new
FileReader("zam.txt"));
String r;
int v =0;
do{
r = br.readLine();
if(r!=null){
v++;
}
}while(r!=null);
Object[] row = new String[v];
do{
r = br.readLine();
if(r!=null){
for (int i = 0; i < v; i++) {
int ix = r.indexOf(";");
row[i] = r.substring(0, ix);
r = r.substring(ix+1);
int zn = r.indexOf(";");
row[i] += r.substring(0, zn);
r = r.substring(zn+1);
int xn = r.indexOf(";");
row[i] += r.substring(0, xn);
r = r.substring(xn+1);
int an = r.indexOf(";");
row[i] += r.substring(0, an);
table.addRow(row);
}
}
}while(r!=null);
br.close();
} catch (IOException e) {
}
}
You should shorten this.
private void jButton4ActionPerformed(java.awt.event.ActionEvent evt)
{
try {
BufferedReader br = new BufferedReader(new
FileReader("zam.txt"));
String r;
do{
r = br.readLine();
if(r!=null){
String [] sline=r.split(";");
table.addRow(sline);
}
}while(r!=null);
br.close();
} catch (IOException e) {
}
}
Reason: you read the file 2 times but without resetting the stream. Why?
Then you counted the number of lines and took this number as number of columns, why?
You count the number of lines in the file
do{
r = br.readLine();
if(r!=null){
v++;
}
}while(r!=null);
After that you try to read from the file, after the EOF has already been reached
do{
r = br.readLine();
if(r!=null){
[...]
}
}while(r!=null);
r = br.readLine(); will return null, since the EOF has been reached, and skip over the loop
To fix this, you can either reopen the file
//counting code
br.close();
br = new BufferedReader([...]);
//reading code
Or you can add the lines to a List instead, and use that
BufferedReader br = new BufferedReader([...]);
List<String> lines = new ArrayList<String>();
for(String line = br.readLine(); line != null; line = br.readLine())
lines.add(line);
String[] row = lines.toArray(new String[0]);
If you're just adding the values to a table, it may be easier to not store the file at all
BufferedReader br = new BufferedReader([...]);
for(String line = br.readLine(); line != null; line = br.readLine())
table.addRow(line.split(";"));

Use Java import CSV file number into array, strange "whitespace" cannot be trimmed

I am using java to import doubles from a excel file into doubles array, here is my code(I steal the second half of the code from another source: https://www.mkyong.com/java/how-to-read-and-parse-csv-file-in-java/):
private static int rows = 10;
private static double[][][] data10;
data10 = new double[rows][2][];
for (int i = 0; i<rows; i++) {
data10[i][0] = new double[16];
data10[i][1] = new double[1];
}
String csvFile = "data.csv";
BufferedReader br = null;
String line = "";
String cvsSplitBy = ",";
try {
br = new BufferedReader(new FileReader(csvFile));
for (int j = 0; j < rows; j++) {
line = br.readLine();
// use comma as separator
String[] values = line.split(cvsSplitBy);
for (int i = 0; i < values.length-1; i++) {
//String temp = values[i];
//System.out.println(temp.trim());
//System.out.println(2);
data10[j][0][i] = Double.valueOf(values[i]);
}
data10[j][1][0] = Double.valueOf(values[values.length - 1].trim());
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (br != null) {
try {
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
i had numberformatexception at this line:
data10[j][0][i] = Double.valueOf(values[i]);
the reason is that the the first cell in the csv file is number 2, however it was shown as " 2" in the exception message. I tried to trim the string, however the "whitespace" cannot be trimmed. I tried to assign values[i] to a String object and trim it yet without success.
Finally I realized that I have to save the file as "comma separated values(.csv)", but not "CSV UTF-8(comma delimited)(.csv)". After correcting this, the code works.
I hope this would help someone. I can't find the answer in other stackoverflow posts.
.trim() replaces whitespace which is represented by unicode '\u0020'. What you might be seeing is a nobreakspace(&nbsp) which is represented by '\u00A0'.
To remove it try: data10[j][0][i] = Double.valueOf(values[i].replaceAll("\\u00A0", ""));

combine two methods in Java together in this Java code

I want combine the two methods Just some error in my document parser, frequencyCounter and parseFiles thsi code.
I want all of frequencyCounter should be a function that should be executed from within parseFiles, and relevant information don't worry about the file's content should be passed to doSomething so that it knows what to print.
Right now I'm just keep messing up on how to put these two methods together, please give some advices
this is my main class:
public class Yolo {
public static void frodo() throws Exception {
int n; // number of keywords
Scanner sc = new Scanner(System.in);
System.out.println("number of keywords : ");
n = sc.nextInt();
for (int j = 0; j <= n; j++) {
Scanner scan = new Scanner(System.in);
System.out.println("give the testword : ");
String testWord = scan.next();
System.out.println(testWord);
File document = new File("path//to//doc1.txt");
boolean check = true;
try {
FileInputStream fstream = new FileInputStream(document);
BufferedReader br = new BufferedReader(new InputStreamReader(fstream));
String strLine;
strLine = br.readLine();
// Read File Line By Line
int count = 0;
while ((strLine = br.readLine()) != null) {
// check to see whether testWord occurs at least once in the
// line of text
check = strLine.toLowerCase().contains(testWord.toLowerCase());
if (check) {
// get the line
String[] lineWords = strLine.split("\\s+");
// System.out.println(strLine);
count++;
}
}
System.out.println(testWord + "frequency: " + count);
br.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
The code below gives you this output:
Professor frequency: 54
engineering frequency: 188
data frequency: 2
mining frequency: 2
research frequency: 9
Though this is only for doc1, you've to add a loop to iterate on all the 5 documents.
public class yolo {
public static void frodo() throws Exception {
String[] keywords = { "Professor" , "engineering" , "data" , "mining" , "research"};
for(int i=0; i< keywords.length; i++){
String testWord = keywords[i];
File document = new File("path//to//doc1.txt");
boolean check = true;
try {
FileInputStream fstream = new FileInputStream(document);
BufferedReader br = new BufferedReader(new InputStreamReader(fstream));
String strLine;
strLine = br.readLine();
// Read File Line By Line
int count = 0;
while ((strLine = br.readLine()) != null) {
// check to see whether testWord occurs at least once in the
// line of text
check = strLine.toLowerCase().contains(testWord.toLowerCase());
if (check) {
// get the line
String[] lineWords = strLine.split("\\s+");
count++;
}
}
System.out.println(testWord + "frequency: " + count);
br.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
hope this helps!

Regular Expression..Splitting a string array twice

I have a text file with state-city values:-
These are the contents in my file:-
Madhya Pradesh-Bhopal
Goa-Bicholim
Andhra Pradesh-Guntur
I want to split the state and the city... Here is my code
FileInputStream fis= new FileInputStream("StateCityDetails.txt");
BufferedInputStream bis = new BufferedInputStream(fis);
int h=0;
String s;
String[] str=null;
byte[] b= new byte[1024];
while((h=bis.read(b))!=-1){
s= new String(b,0,h);
str= s.split("-");
}
for(int i=0; i<str.length;i++){
System.out.println(str[1]); ------> the value at 1 is Bhopal Goa
}
}
Also I have a space between Madhya Pradesh..
So i want to Remove spaces between the states in the file and also split the state and city and obtain this result:-
str[0]----> MadhyaPradesh
str[1]----> Bhopal
str[2]-----> Goa
str[3]----->Bicholim
Please Help..Thank you in advance :)
I would use a BufferedReader here, rather than the way you are doing it. The code snippet below reads each line, split on hyphen (-), and removes all whitespace from each part. Each component is entered into a list, in left to right (and top to bottom) order. The list is converted to an array at the end in case you need this.
List<String> names = new ArrayList<String>();
BufferedReader br = null;
try {
String currLine;
br = new BufferedReader(new FileReader("StateCityDetails.txt"));
while ((currLine = br.readLine()) != null) {
String[] parts = currLine.split("-");
for (int i=0; i < parts.length; ++i) {
names.add(parts[i].replaceAll(" ", ""));
}
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (br != null) br.close();
} catch (IOException ex) {
ex.printStackTrace();
}
}
// convert the List to an array of String (if you require it)
String[] nameArr = new String[names.size()];
nameArr = names.toArray(nameArr);
// print out result
for (String val : nameArr) {
System.out.println(val);
}

java read only integers from file

If I have a file that contains for example:
results1: 2, 4, 5, 6, 7, 8, 9
results2: 5, 3, 7, 2, 8, 5, 2
I want to add the integers from each line to a array. One array
for each line. How can I do this with code that does only read the integers?
Here's what I got this far
String data = null;
try {
Scanner in = new Scanner(new File(myFile));
while (in.hasNextLine()) {
data = in.nextLine();
numbers.add(data);
}
in.close();
} catch (Exception e) {
}
Easy.
One line per array, not two as you have it. New line after each one.
Read each line as a String, discard the leading "resultsX:", and split what remains at a delimiter of your choosing (e.g. comma). Parse each into an integer and add it to a List.
I don't think that leading "results1: " is adding any value. Why do you have that?
public static void main(String[] args) throws IOException {
BufferedReader reader=null;
try {
reader = new BufferedReader(new FileReader(new File("PATH TO FILE")));
// Only works if File allways contains at least two lines ... all lines after the second
// will be ignored
System.out.println(String.format("Array 1 : %s", Arrays.toString(stringArray2IntArray(readNextLine(reader)))));
System.out.println(String.format("Array 2 : %s", Arrays.toString(stringArray2IntArray(readNextLine(reader)))));
} finally {
if (reader!=null) {
reader.close();
}
}
}
private static Integer[] stringArray2IntArray(String[] numStrings) {
List<Integer> result = new ArrayList<Integer>();
for (int i = 0; i < numStrings.length; i++) {
result.add(Integer.parseInt(numStrings[i].trim()));
}
return result.toArray(new Integer[numStrings.length]);
}
private static String[] readNextLine(BufferedReader reader) throws IOException {
return reader.readLine().split(":")[1].split(",");
}
Assuming you have an input file, like this:
2,4,5,6,7,8,9
5,3,7,2,8,5,2
here is a code snippet to load it:
String firstLine = "";
String secondLine = "";
File file = new File("path/to/file");
try {
BufferedReader br = new BufferedReader(new FileReader(file));
firstLine = br.readLine();
secondLine = br.readLine();
} catch(Exception e){
e.printStackTrace();
}
String[] firstResult = firstLine.split(",");
String[] secondResult = secondLine.split(",");
int[] firstIntegers = new int[firstResult.length];
for(int i = 0; i <= firstResult.length ; i++){
firstIntegers[i] = Integer.parseInt(firstResult[i]);
}
int[] secondIntegers = new int[secondResult.length];
for(int i = 0; i <= secondResult.length ; i++){
firstIntegers[i] = Integer.parseInt(secondResult[i]);
}
Open the file with a BufferedReader br and then read it line by line.
Store each line in an int array and add all those int arrays to a list. At the end, this list will contain all the int arrays that we wanted, so iterate this list to do whatever you want to do next.
String filePath = "/path/to/file";
BufferedReader br = null;
List<Integer[]> arrays = new ArrayList<>(); //this contains all the arrays that you want
try {
br = new BufferedReader(new FileReader(filePath));
String line = null;
while ((line = br.readLine()) != null) {
line = line.substring(line.indexOf(":")+2); //this starts the line from the first number
String[] stringArray = line.split(", ");
Integer[] array = new Integer[stringArray.length];
for (int i = 0; i < stringArray.length; ++i) {
array[i] = Integer.parseInt(stringArray[i]);
}
arrays.add(array);
}
} catch (FileNotFoundException ex) {
System.err.println(ex);
} catch (IOException ex) {
System.err.println(ex);
} finally {
try {
br.close();
} catch (Exception ex) {
System.err.println(ex);
}
}
Since ArrayLists keep insertion order, then, e.g., arrays.get(3) will give you the array of the fourth line (if there is such a line) and arrays.size() will give you the number of lines (i.e., int arrays) that are stored.

Categories