how to make the users appear once while reading a csv file? - java

I have a program I wrote that can read a csv file. The csv file have two columns one for clusters number and the other is for users. what I need for the program is not to repeat the user. Instead, to write the user once and in each cluster to simply write 1 if the user had shown in that cluster number.
package parsing;
public static void main(String[]args){
String fileName= "ClusterResult(final1).csv";//reading the file
File file = new File(fileName);
try {
Scanner inputStream = new Scanner(file);
while (inputStream.hasNext()){
String data = inputStream.next();
String [] myArray= data.split(",");
for(int i =0; i<=27;i++){// because I have 27 clusters
Arrays.sort(myArray);
int founditem= Arrays.binarySearch(myArray, String.valueOf(i));
if (founditem>-1 )
System.out.print("1"); //if the user name showed in the cluster the user should have one next to the cluster number
else
System.out.print("0");
}
System.out.println();
System.out.println(myArray[1] );
}
inputStream.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
the output of the program is :
1000000000000000000000000000
ElDaddy
1000000000000000000000000000
Lxve
1000000000000000000000000000
Lxve
0000001000000000000000000000
ElDaddy
where it should be for example :
1000001000011000010100000000
ElDaddy

You say in your question your csv has two columns, if that's true, try something like this:
public static void main(String[] args) {
HashMap<String, HashSet<String>> map = new HashMap<String, HashSet<String>>();
String fileName = "ClusterResult(final1).csv";// reading the file
FileReader file = null;
try {
file = new FileReader(new File(fileName));
} catch (FileNotFoundException e1) {
System.err.println("File " + fileName + " not found!");
e1.printStackTrace();
}
BufferedReader br = new BufferedReader(file);
String line;
try {
while ((line = br.readLine()) != null) {
String[] data = line.split(",");
generateClusters(data[0], data[1], map);
}
for (Entry<String, HashSet<String>> entry : map.entrySet()) {
for (int i = 0; i < 27; i++) {
if (entry.getValue().contains(String.valueOf(i)))
System.out.print(1);
else
System.out.print(0);
}
System.out.println();
System.out.println(entry.getKey());
}
} catch (IOException e) {
System.err.println("Error when reading");
e.printStackTrace();
} finally {
if (br != null) {
try {
br.close();
} catch (IOException e) {
System.err.println("Unexpected error");
e.printStackTrace();
}
}
}
}
public static void generateClusters(String e1, String e2,
HashMap<String, HashSet<String>> map) {
HashSet<String> clustersOfUser = map.get(e1);
if (clustersOfUser == null) {
clustersOfUser = new HashSet<String>();
map.put(e1,clustersOfUser);
}
clustersOfUser.add(e2);
}
What we are doing here is grouping the users in a HashMap, but storing the clusters
as keys.

Related

Searching string from text file

I'm trying to search a certain string from an input file. Firstly, the code stores data from input file and then it searches the user input data in the text file, but when i try to print one of the variables it ends up being null.
public class Test {
public static void main(String args[])throws IOException, FileNotFoundException {
BufferedReader input = null;
PrintWriter output = null;
try {
input = new BufferedReader (new FileReader ("kolej.txt"));
Scanner in = new Scanner(System.in);
in.useDelimiter("\n");
int index = 0;
String indata = null;
System.out.println("UITM College and Non-Residents Registration System");
System.out.println("Enter your student id: ");
String matrix = in.next();
UITM student[] = new UITM[10];
//storing data into array
while ((indata = input.readLine())!= null) {
StringTokenizer st = new StringTokenizer(indata,";");
student[index] = new Kolej(st.nextToken(), st.nextToken(), st.nextToken(), Integer.parseInt(st.nextToken()), st.nextToken(),Integer.parseInt(st.nextToken()), st.nextToken(),Integer.parseInt(st.nextToken())) ;
index++;
}
//searching
Scanner txtscan = new Scanner(new File("kolej.txt"));
while(txtscan.hasNextLine()) {
matrix = txtscan.nextLine();
if(matrix.indexOf("word") != -1) {
System.out.println(student[0].getName());
}
}
input.close();
output.close();
}
catch (FileNotFoundException fnfe) {
System.out.println("File not found");
}
catch (IOException ioe) {
System.out.println(ioe.getMessage());
}
catch (Exception e) {
System.out.println(e.getMessage());
}
}
}

Java - parse CSV into Arrays based on columns

I would like to ask for help with this task:
I have CSV for example like this:
column1$column2$column3
123$xyz$321
456$zyx$654
And I would like to parse it by Java to Arrays / Array lists by columns / headers -> for example
ArrayList column1 = [123,456]
ArrayList column2 = [xyz,zyx]
ArrayList column3 = [321,654]
Thanks everyone.
This is how I would have done this..., note the metod to put the columns in another List for less code and to be more dynamic.
public static void main(String[] args) {
ArrayList<ArrayList<String>> columns = new ArrayList<ArrayList<String>>();
BufferedReader br = null;
try {
String sCurrentLine;
br = new BufferedReader(new FileReader("testing.cvs"));
while ((sCurrentLine = br.readLine()) != null) {
String[] fields = sCurrentLine.split("\\$");
for (int i = 0; i < fields.length; i++) {
if (columns.size()<=i){
columns.add(new ArrayList<String>());
}
columns.get(i).add(fields[i]);
}
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (br != null)br.close();
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
I thin this can help you to fix the problem just tery it.
public static void main(String[] args) {
Scanner s = null;
try {
s = new Scanner(new File("C:\\temp\\file.txt"));
ArrayList lis1 = new ArrayList();
ArrayList lis2 = new ArrayList();
ArrayList lis3 = new ArrayList();
while (s.hasNext()) {
String d = s.nextLine();
lis1.add(d.split("\\$")[0]);
lis2.add(d.split("\\$")[1]);
lis3.add(d.split("\\$")[2]);
}
for (Object l : lis1) {
System.out.print(l+" ");
}
System.out.print("\n ");
for (Object l : lis2) {
System.out.print(l+" ");
}
System.out.print("\n ");
for (Object l : lis3) {
System.out.print(l+" ");
}
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
you can use the result when you wont

How to pass parameter to data provider in testng from csv file

Am reading data from csv file , i have test for which this data will be the input .
i want it to run as tescase for every set of value. for that am using data provider
The problem is , it is taking only the last set row of data , please help me in debugging the code
For eg : if my csv has following data
name1 id1 text1
name2 id2 text2
name3 id3 text3
it taking only last row name3 id3 text3 and running the test only once not three times.
#DataProvider(name = "test")
public Object[][] provider( ) throws InterruptedException
{
Object[][] returnObject ;
String[] checkpoint = ReadfromCSV();
count = count + 1;
returnObject = new Object[][]{checkpoint };
return returnObject;
}
#Test(description = "Test", groups = "test" , dataProvider = "test")
public void compare(String val1,String val2,String val3,String val4,String val5,String val6,String val7,String val8,String val9,String val10,String val11 ) {
System.out.println("1:" + val1);
System.out.println("4:" + val2);
System.out.println("5:" + val3);
}
#SuppressWarnings("null")
public String[] ReadfromCSV() throws InterruptedException {
String[] data= null;
String csvFile = "F:/sample1.csv";
BufferedReader br = null;
String line = "";
String cvsSplitBy = ",";
try {
br = new BufferedReader(new FileReader(csvFile));
while ((line = br.readLine()) != null) {
// use comma as separator
data= line.split(cvsSplitBy);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (br != null) {
try {
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
System.out.println("Done");
return data;
}
You should read entire file in data provider and return iterator of test cases. Here is some pseudocode for data provider. Notice that I used List<String []> to store test cases instead of Object[][]. This allows you do define test cases dynamically.
#DataProvider(name = "test")
public Iterator<Object []> provider( ) throws InterruptedException
{
List<Object []> testCases = new ArrayList<>();
String[] data= null;
//this loop is pseudo code
br = new BufferedReader(new FileReader(csvFile));
while ((line = br.readLine()) != null) {
// use comma as separator
data= line.split(cvsSplitBy);
testCases.add(data);
}
return testCases.iterator();
}
public String[][] ReadfromCSV() throws InterruptedException {
int count =0;
String[] data= null;
String returnObj[][] = null;
//System.out.println(System.getProperty("user.dir"));
String csvFile = System.getProperty("user.dir")+ "/src/test/resources/testdata.csv";
BufferedReader br = null;
String line = "";
String cvsSplitBy = ",";
ArrayList<String> content = new ArrayList<String>();
try {
//this loop is pseudo code
br = new BufferedReader(new FileReader(csvFile));
int datalength = 0;
int listsize =0;;
while ((line = br.readLine()) != null) {
// use comma as separator
content.add(line);
}
System.out.println(content);
listsize = content.size();
datalength = content.get(0).split(cvsSplitBy).length;
returnObj = new String[listsize][datalength];
for (int i = 0; i<listsize; i++) {
data = content.get(i).split(cvsSplitBy);
for (int j=0; j< datalength ; j++) {
returnObj[i][j] = data[j];
}
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (br != null) {
try {
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
System.out.println("Done");
return returnObj;
}}

Reading into a string from a file, but any text after space on a line removed?

I have a large text file with phrases such as:
citybred JJ
Brestowe NNP
STARS NNP NNS
negative JJ NN
investors NNS NNPS
mountain NN
My objective is to keep the first word of each line, without the spaces, and also make them lowercase.
EX:
citybred
brestowe
stars
negative
investors
mountain
Would be returned if the above text was evaluated.
Any help?
Current code:
public class FileLinkList
{
public static void main(String args[])throws IOException{
String content = new String();
File file = new File("abc.txt");
LinkedList<String> list = new LinkedList<String>();
try {
Scanner sc = new Scanner(new FileInputStream(file));
while (sc.hasNextLine()){
content = sc.nextLine();
list.add(content);
}
sc.close();
} catch(FileNotFoundException fnf){
fnf.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
System.out.println("\nProgram terminated Safely...");
}
Collections.reverse(list);
Iterator i = list.iterator();
while (i.hasNext()) {
System.out.print("Node " + (count++) + " : ");
System.out.println(i.next());
}
}
}
If your token and its POS tag is separated by space :
public class FileLinkList{
public static void main(String[] args) {
BufferedReader br = null;
LinkedList<String> list = new LinkedList<String>();
String word;
try {
String sCurrentLine;
br = new BufferedReader(new FileReader("LEXICON.txt"));
while ((sCurrentLine = br.readLine()) != null) {
System.out.println(sCurrentLine);
word = sCurrentLine.trim().split(" ")[0];
list.add(word.toLowerCase());
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (br != null)
br.close();
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
}
Add the following:
content = sc.nextLine();
string[] tokens = content.split(new char[] {' '}, StringSplitOptions.RemovEemptyEntries);
// You can add some validations here...
string word = tokens[0].ToLowerCase();
Try this :
public class FileLinkList {
public static void main(String args[])throws IOException{
String content = new String();
int count=1;
File file = new File("abc.txt");
LinkedList<String> list = new LinkedList<String>();
try {
Scanner sc = new Scanner(new FileInputStream(file));
while (sc.hasNextLine()){
content = sc.nextLine();
if (content != null && content.length() > 0)) {
list.add(content.trim().split(" ")[0].toLowerCase());
}
}
sc.close();
} catch(FileNotFoundException fnf){
fnf.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
System.out.println("\nProgram terminated Safely...");
}
for (String listItem : list) {
System.out.println(listItem);
}
}
}
With Apache Commons IO it is much simpler to read a file into a list of Strings.
import org.apache.commons.io.FileUtils;
List<String> lines = FileUtils.readLines(new File("abc.txt"));
List<String firstWords = new ArrayList<>();
for (String line : lines) {
String firstWord = line.split(" ")[0].toLowerCase();
firstWords.add(firstWord);
}

converting lines of imported text file to arrays and printing arrays to make graph in Netbeans and Swing

I want to import any .txt files (note the .txt files will have a 3 sets of numbers in one column; separating each set with a space)
2
3
4
3
2
1
1
2
3
and convert the set of numbers into arrays. (array 1 , 2 and 3)
array1[] = {2,3,4}
array2[] = {3,2,1}
array3[] = {1,2,3}
then be able to graph the array in JFreeGraph Library
here's how i started...i'm using netbeans and java Swing
#Action
public void openMenuItem() {
int returnVal = jFileChooser1.showOpenDialog(null);
if (returnVal == JFileChooser.APPROVE_OPTION) {
File file = jFileChooser1.getSelectedFile();
try {
FileReader fileReader = new FileReader(file);
jTextArea2.read(new FileReader(file.getAbsolutePath()), null);
} catch (IOException ex) {
System.out.println("problem accessing file" + file.getAbsolutePath());
}
} else {
System.out.println("File access cancelled by user.");
}
}
Read from a file line by line, perhaps using BufferedReader and readLine. Once you encounter an empty line - you have a new set of numbers. Here is an oversimplified example that maintains a list of lists, and reads only strings:
public static List<List<String>> parseFile(String fileName){
BufferedReader bufferedReader = null;
List<List<String>> lists = new ArrayList<List<String>>();
List<String> currentList = new ArrayList<String>();
lists.add(currentList);
try {
bufferedReader = new BufferedReader(new FileReader(fileName));
String line = null;
while ((line = bufferedReader.readLine()) != null) {
if (line.isEmpty()){
currentList = new ArrayList<String>();
lists.add(currentList);
} else {
currentList.add(line);
}
}
} catch (FileNotFoundException ex) {
ex.printStackTrace();
} catch (IOException ex) {
ex.printStackTrace();
} finally {
try {
if (bufferedReader != null)
bufferedReader.close();
} catch (IOException ex) {
ex.printStackTrace();
}
}
return lists;
}
EDIT: using resulting lists with JTextArea
List<List<String>> lists = parseFile("test.txt");
for (List<String> strings : lists){
textArea.append(StringUtils.join(strings, ",") + "\n");
System.out.println(StringUtils.join(strings, ","));
}

Categories

Resources