I have a txt file that contains 24 columns separated with \t. The first column contains words and the other 23 columns contain int (0 or 1). I need to put each column in a separate file
For example:
file.txt
xyz 0 1
abc 0 1
the resulting files would be:
file 1:
0
0
file 2:
1
1
The code is as follows:
for (int i=24; i>0; i--){
//copy the last word (column) in list
for (String str: list) {
String ch = str.substring(str.length() - 1);
col_list.add(ch);
}
//write the column in file
FileWriter write = new FileWriter(+i+".txt");
for(String str1: col_list) {
write.write(str1+"\n");
}
write.close();
col_list = new ArrayList<String>();
//remove last column from list
for(String str2: list) {
str2.substring(str2.length()-3, str2.length()-1);
}
}
The result files contain only the content of the last column
file 1:
1
1
file 2:
1
1
How about going for it this way? Change num_files to 24 and you should be good to go.
import java.util.ArrayList;
import java.util.Scanner;
import java.io.FileWriter;
import java.io.File;
class Test {
public static void main(String a[]) {
File myFile = new File("Test.txt");
try {
int num_files = 3;
Scanner scanner = new Scanner(myFile);
String list[];
while (scanner.hasNextLine()) {
list = scanner.nextLine().split("\t");
for (int i = 0; i < num_files; i++) {
FileWriter write = new FileWriter((i + 1) + ".txt", true); //you want to open it in append mode
write.write(list[i] + "\n");
write.close();
}
}
} catch (Exception e) {
}
}
}
Input and Output Files
Let me know if this solves your problem. Cheers!
Related
i want to write a code that stores strings in a hashmap as they are read from text files.
i have written the code below and it works, no errors, the frequency of every occurrence of the string combination does not change, it is always 1.
i am asking for assistance on how i can ensure that if a string combination appears more than once in the text file then its frequency should also increase.
this is my code:
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.*;
public class NgramBetaC {
static String[] hashmapWord = null;
public static Map<String,Map<String, Integer>> bigrams = new HashMap<>();
public static void main(String[] args) {
//prompt user input
Scanner input = new Scanner(System.in);
//read words from collected corpus; a number of .txt files
File directory = new File("Corpus4");
File[] listOfFiles = directory.listFiles();//To read from all listed iles in the "directory"
//String bWord[] = null;
int lineNumber = 0;
String line;
String files;
String delimiters = "[\\s+,?!:;.]";
int wordTracker = 0;
//reading from a list of text files
for (File file : listOfFiles) {
if (file.isFile()) {
files = file.getName();
try {
if (files.endsWith(".txt") || files.endsWith(".TXT")) { //ensures a file being read is a text file
BufferedReader br = new BufferedReader(new FileReader(file));
while ((line = br.readLine()) != null) {
line = line.toLowerCase();
hashmapWord = line.split(delimiters);
for(int s = 0; s < hashmapWord.length - 2; s++){
String read = hashmapWord[s];
String read1 = hashmapWord[s + 1];
final String read2 = hashmapWord[s + 2];
String readBigrams = read + " " + read1;
final Integer count = null;
//bigrams.put(readBigrams, new HashMap() {{ put (read2, (count == null)? 1 : count + 1);}});
bigrams.put(readBigrams, new HashMap<String, Integer>());
bigrams.get(readBigrams).put(read2, (count == null) ? 1 : count+1);
} br.close();
}
}
} catch (NullPointerException | IOException e) {
e.printStackTrace();
System.out.println("Unable to read files: " + e);
}
}
}
}
THE LINES CONTAINED IN THE TEXT FILES ARE::
1.i would like some ice cream.
2.i would like to be in dubai this december.
3.i love to eat pasta.
4.i love to prepare pasta myself.
5.who will be coming to see me today?
THE OUTPUT I GET WHEN PRINTING CONTENTS OF THE HASHMAP IS:
{coming to={see=1}, would like={to=1}, in dubai={this=1}, prepare pasta={myself=1}, to eat={pasta=1}, like to={be=1}, to prepare={pasta=1}, will be={coming=1}, love to={prepare=1}, some ice={cream=1}, be in={dubai=1}, be coming={to=1}, dubai this={december=1}, to be={in=1}, i love={to=1}, to see={me=1}, who will={be=1}, like some={ice=1}, i would={like=1}, see me={today=1}}
Please assist! some string combinations are not even appearing.
THE OUTPUT I EXPECT AS I READ FROM THE FILES IS:
{coming to={see=1}, would like={to=1}, in dubai={this=1}, prepare pasta={myself=1}, to eat={pasta=1}, like to={be=1}, to prepare={pasta=1}, will be={coming=1}, love to={prepare=1}, some ice={cream=1}, be in={dubai=1}, be coming={to=1}, dubai this={december=1}, to be={in=1}, i love={to=1}, to see={me=1}, who will={be=1}, like some={ice=1}, i would={like=2}, see me={today=1}, love to {eat=1}, would like {some=1}, i would {love=1}, would love {to=1}}
Tentatively update the current structure without overwriting the originl content
Replace
bigrams.put(readBigrams, new HashMap<String, Integer>());
bigrams.get(readBigrams).put(read2, (count == null) ? 1 : count+1);
With
HashMap<String, Integer> counter = bigrams.get(readBigrams);
if (null == counter) {
counter = new HashMap<String, Integer>();
bigrams.put(readBigrams, counter);
}
Integer count = counter.get(read2);
counter.put(read2, count == null ? 1 : count + 1);
for this program I have to write I'm given an input file of strings that has a line (or lines) of text, for example: "The high HIGH cat High jumped (WOW 6SOFT)". From this line I have to scan the file, count the number of times a word appears (regardless of capitalization), and then output it to a formatted file. If a digit comes before a word, the word should not be counted. The format has to be started with the count right justified in three spaces, followed by another space, followed by the word counted in lower case.
package InClass;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Scanner;
public class CountWords {
public static void main(String[] args) {
try {
File inputFile = new File("input.txt");
Scanner scanner = new Scanner(inputFile);
File outputFile = new File("output.txt");
PrintWriter writer = new PrintWriter(outputFile);
boolean next = scanner.hasNext();
ArrayList<String> inputWords = new ArrayList<String>();
ArrayList<String> outputWords = new ArrayList<String>();
while (next) { // Adds all the strings to an array list
inputWords.add(scanner.next());
for (int i = 0; i < inputWords.size(); i++) {
inputWords.get(i).toLowerCase();
}
}
while (next) {
for (int i = 0; i < inputWords.size(); i++) {
String word = inputWords.get(i);
int count = 1;
if (!Character.isDigit(word.charAt(0))) {
outputWords.add(inputWords.get(i));
if (outputWords.contains(word)) {
count++;
}
} else {
inputWords.remove((i));
}
for (int j = 0; i < outputWords.size(); j++) {
word = outputWords.get(i);
writer.printf("%3s" + "%1s\n", count, word);
}
}
}
scanner.close();
writer.close();
} catch (FileNotFoundException e) {
}
}
}
My tester file is giving me an error saying there is a NoSuchElementException for only one of the tester classes, which is testing two words. Here is the test class giving the error"
#Test
public void testTwoWords() {
try {
File inputFile = new File(INPUT);
File outputFile = new File(OUTPUT);
// If assert fails it is (usually) because the file was (wrongly)
// left open in an earlier run.
// Using a file manager application (e.g. explorer), go to project
// directory and delete it.
// Make sure that your program closes these files before ending.
if (inputFile.exists()) {
assertTrue("Your program left \"" + INPUT
+ "\" open in a previous test.", inputFile.delete());
}
if (outputFile.exists()) {
assertTrue("Your program left \"" + OUTPUT
+ "\" open in a previous test.", outputFile.delete());
}
// create INPUT file
PrintWriter input = new PrintWriter(inputFile);
input.println("King");
input.println("");
input.println("");
input.println("");
input.println("hill");
input.close();
// invoke program
CountWords.main(null);
// verify OUTPUT file exists and is empty
assertTrue("Output file doesn't exist", outputFile.exists());
Scanner output = new Scanner(outputFile);
String actual = output.nextLine();
assertEquals("Incorrect result", " 1 king", actual);
actual = output.nextLine();
assertEquals("Incorrect result", " 1 hill", actual);
assertFalse("There should be no more data", output.hasNext());
output.close();
// delete I/O files
assertTrue("Input file could not be deleted", inputFile.delete());
assertTrue("Output file could not be deleted", outputFile.delete());
} catch (IOException e) {
fail("No exception should be thrown");
}
}
Finally, my other testers are saying "Your program left "input.txt" open in a previous test". Any idea why? Thank you tons in advance!
The for loop for your outputWords is using the i loop counter instead of j.
for (int j = 0; i < outputWords.size(); j++) {
word = outputWords.get(i);
writer.printf("%3s" + "%1s\n", count, word);
}
Change that to
for (int j = 0; i < outputWords.size(); j++) {
word = outputWords.get(j);//NEED TO USE J HERE
writer.printf("%3s" + "%1s\n", count, word);
}
The reason the other tests are failing is because you are apparently supposed to delete the output files after each test is run.
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
I am new to java
Can anyone help me with the code to tell how much 2 text files match with each other?
Suppose i have two Files 'a.txt' and 'b.txt'
then i need to know the percentage of match.
thanks
Read in the two files to two Strings str1, str2.
Iterate through each, counting matching chars. Divide number of matches by number of compares, and multiply by 100 to get a percentage.
Scanner sca = new Scanner(new File ("a.txt"));
Scanner scb = new Scanner(new File ("b.txt"));
StringBuilder sba = new StringBuilder();
StringBuilder sbb = new StringBuilder();
while(sca.hasnext()){
sba.append(sca.next());
}
while(scb.hasnext()){
sbb.append(scb.next());
}
String a = sba.toString();
String b = sbb.toString();
int maxlen = Math.max(a.length,b.length);
int matches;
for(int i =0; i<maxlen; i++){
if(a.length <=i || b.length <=i){
break;
}
if(a.chatAt(i)==b.charAt(i)){
matches++;
}
return (((double)matches/(double)maxlen)*100.0)
import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.Reader;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Scanner;
import java.util.StringTokenizer;
class File_meta_Data // class to store the metadata of file so that scoring can be done
{
String FileName;
long lineNumber;
long Position_In_Line;
long Position_In_Document;
File_meta_Data()
{
FileName = null;
lineNumber = 0;
Position_In_Line = 0;
Position_In_Document = 0;
}
}
public class bluestackv1 {
static int getNumberofInputFiles() // seeks number of resource files from user
{
System.out.println("enter the number of files");
Scanner scan = new Scanner(System.in);
return(scan.nextInt());
}
static List getFiles(int Number_of_input_files) // seeks full path of resource files from user
{
Scanner scan = new Scanner(System.in);
List filename = new ArrayList();
int i;
for(i=0;i<Number_of_input_files;i++)
{
System.out.println("enter the filename");
filename.add(scan.next());
}
return(filename);
}
static String getfile() // seeks the full pathname of the file which has to be matched with resource files
{
System.out.println("enter the name of file to be matched");
Scanner scan = new Scanner(System.in);
return(scan.next());
}
static Map MakeIndex(List filename) // output the index in the map.
{
BufferedReader reader = null; //buffered reader to read file
int count;
Map index = new HashMap();
for(count=0;count<filename.size();count++) // for all files mentioned in the resource list create index of its contents
{
try {
reader = new BufferedReader(new FileReader((String) filename.get(count)));
long lineNumber;
lineNumber=0;
int Count_of_words_in_document;
Count_of_words_in_document = 0;
String line = reader.readLine(); // data is read line by line
while(line!=null)
{
StringTokenizer tokens = new StringTokenizer(line, " ");// here the delimiter is <space> bt it can be changed to <\n>,<\t>,<\r> etc depending on problem statement
lineNumber++;
long Count_of_words_in_line;
Count_of_words_in_line = 0;
while(tokens.hasMoreTokens())
{
List<File_meta_Data> temp = new ArrayList<File_meta_Data>();
String word = tokens.nextToken();
File_meta_Data metadata = new File_meta_Data();
Count_of_words_in_document++; // contains the word number in the document
Count_of_words_in_line++; // contains the word number in line. used for scoring
metadata.FileName = filename.get(count).toString();
metadata.lineNumber = lineNumber;
metadata.Position_In_Document = Count_of_words_in_document;
metadata.Position_In_Line = Count_of_words_in_line;
int occurence;
occurence=0;
if(index.containsKey(word)) //if the word has occured already then update the new entry which concatenates the older and new entries
{
Map temp7 = new HashMap();
temp7 = (Map) index.get(word);
if(temp7.containsKey(metadata.FileName)) // entry of child Map is changed
{
List<File_meta_Data> temp8 = new ArrayList<File_meta_Data>();
temp8 = (List<File_meta_Data>)temp7.get(metadata.FileName); //outputs fioles which contain the word along with its location
temp7.remove(metadata.FileName);
temp8.add(metadata);
temp7.put(metadata.FileName, temp8); // updated entry is added
}
else // if the word has occured for the first time and no entry is in the hashMap
{
temp.add(metadata);
temp7.put(metadata.FileName, temp);
temp=null;
}
Map temp9 = new HashMap();
temp9 = (Map) index.get(word);
index.remove(word);
temp9.putAll(temp7);
index.put(word, temp9);
}
else // similarly is done for parent map also
{
Map temp6 = new HashMap();
temp.add(metadata);
temp6.put(metadata.FileName, temp);
index.put(word,temp6);
}
}
line = reader.readLine();
}
index.put("#words_in_file:"+(String)filename.get(count),Count_of_words_in_document);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return(index);
}
static String search(Map index,List filename) throws IOException //scores each resource file by comparing with each word in input file
{
double[] overlap = new double[filename.size()]; //stores overlap/coord scores
double[] sigma = new double[filename.size()]; // stores ∑t in q ( tf(t in d) · idf(t)^2 for each resource file
int i;
double max, maxid; // stores file info with max score
max=0;
maxid= -1;
for(i=0;i<filename.size();i++)
{
overlap[i] = 0;
sigma[i] = 0;
}
String bestfile = new String();
double maxscore;
maxscore = -1;
double total;
double cord;
total=0;
File File_to_be_matched = new File(getfile());
BufferedReader reader = new BufferedReader(new FileReader(File_to_be_matched));
String line = reader.readLine();
while(line!=null) //similar to index function
{
StringTokenizer tokens = new StringTokenizer(line, " ");
while(tokens.hasMoreTokens())
{
String word = tokens.nextToken();
double tf,idf;
tf = 0;
idf = 0;
total=total+1;
if(index.containsKey(word))
{
Map temp = new HashMap();
for(i=0;i<filename.size();i++) // for each file a score is calculated for corresponding word which afterwards added
{
int j,count,docFreq;
count=0;
docFreq=0;
temp = (Map) index.get(word);
if(temp.containsKey(filename.get(i)))
{
List l2= (List) temp.get(filename.get(i));
tf = (int) Math.pow((long) l2.size(),0.5); //calculate the term frequency
docFreq = temp.size(); // tells in how many files the word occurs in the file
overlap[i]++;
}
else
{
tf=0;
}
idf = (int) (1 + Math.log((long)(filename.size())/(1+docFreq)));// more the occurence higher similarity of file
sigma[i] = sigma[i] + (int)(Math.pow((long)idf,2) * tf);
}
}
}
line = reader.readLine();
}
double subsetRatio;
for(i=0;i<filename.size();i++) // all scores are added
{
int x = (int)index.get("#words_in_file:"+(String)filename.get(i));
subsetRatio = overlap[i]/x;
overlap[i] = overlap[i]/total;
overlap[i] = overlap[i] * sigma[i];
overlap[i] = overlap[i] * subsetRatio; // files which are subset of some have higher priority
if(max<overlap[i]) // maximum score is calculated
{
max=overlap[i];
maxid = i;
}
}
if(maxid!=-1)
return (String) (filename.get((int) maxid));
else
return("error: Matching does not took place");
}
public static void main(String[] args) throws IOException
{
List filename = new ArrayList();
int Number_of_input_files = getNumberofInputFiles();
filename = getFiles(Number_of_input_files);
Map index = new HashMap();
index = MakeIndex(filename);
//match(index);
while(1==1) //infinite loop
{
String Most_similar_file = search(index,filename);
System.out.println("the most similar file is : "+Most_similar_file);
}
}
}
The problem is to find the most similar file among several resource files.
there are 2 sub-problems to this question
first, as the question states, how to find the most similar file which is done by associating each file with a score by considering different aspects of the content of files
second, to parse each and every word of the input file with a comparatively large resource files
to solve the second problem, Reverse Indexing has been used with HashMaps in java. Since our problem was simple and not modifying i used Inherited Maps instead of Comparator based MapReduce
while searching computing complexity = o(RESOURCEFILES * TOTAL_WORDS_IN _INPUTFILE)
the first problem has been solved by following formula
score(q,d) = coord(q,d) • ∑t in q ( tf(t in d) • idf(t)^2) . subsetRatio
1) coord(q,d) = overlap / maxOverlap
Implication: of the terms in the query, a document that contains more terms will have a higher score
Rational : Score factor based on how many of the query terms are found in the specified document
2) tf(t in d) = sqrt(freq)
Term frequency factor for the term (t) in the document (d).
Implication: the more frequent a term occurs in a document, the greater its score
Rationale: documents which contains more of a term are generally more relevant
3) idf(t) = log(numDocs/(docFreq+1)) + 1 I
implication: the greater the occurrence of a term in different documents, the lower its score
Rational : common terms are less important than uncommon ones
4) SubsetRation = number of occuring words / total words
implication : suppose 2 files, both superlative of input file then file with lesser excessive data will have hiegher similarity
Rational : files with similar content must have higher priority
****************test cases************************
1) input file has no similar word than the resource files
2) input file is similar in content to any one of the file
3) input file is similar in content but different in metadata(meaning position of words is not similar)
4) input file is a subset of resource files
5) input file contains very common words like all 'a' or 'and'
6) input file is not at the location
7) input file cannot be read
Look into opening files, reading them as characters. You actually just need to get a char from each, then check if they match. If they match, then increment the total counter and the match counter. If they don't, only the total counter.
Read more on handling files and streams here: http://docs.oracle.com/javase/tutorial/essential/io/charstreams.html
An example would be this:
BufferedReader br1 = null;
BufferedReader br2 = null;
try
{
br1 = new BufferedReader(new InputStreamReader(new FileInputStream(new File("a.txt")), "UTF-8"));
br2 = new BufferedReader(new InputStreamReader(new FileInputStream(new File("b.txt")), "UTF-8"));
//add logic here
}
catch (Exception e)
{
e.printStackTrace();
}
finally
{
if (br1 != null)
{
try
{
br1.close();
}
catch (Exception e)
{
}
}
if (br2 != null)
{
try
{
br2.close();
}
catch (Exception e)
{
}
}
}
I am currently writing my thesis, and in that context I need to develop a meta-heuristic using java. However I am facing a problem when trying to read and store the data.
My file is a text file, with around 150 lines. An example of the problem is in line 5 where three integer numbers are stated: 30, 38 and 1. I would like to store each of these as an integer called respectively L, T and S, and this goes on for many other of the lines.
Any of you who knows how to do that? If needed I can send you the txt file.
btw: this is what I've tried so far:
Main.java:
import java.io.IOException;
import java.io.FileWriter;
import java.io.BufferedWriter;
public class MAIN {
public static void main(String[] args) throws IOException {
Test.readDoc("TAP_T38L30C4F2S12_03.txt");
}
}
Test.java:
import java.io.*;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
public class Test {
private static ArrayList<Integer> integerList = new ArrayList<Integer>();
public static Map<String, ArrayList<Integer>> data = new HashMap<String, ArrayList<Integer>>();
public static String aKey;
public static void readDoc(String File) {
try{
FileReader fr = new FileReader("TAP_T38L30C4F2S12_03.txt");
BufferedReader br = new BufferedReader(fr);
while(true) {
String line = br.readLine();
if (line == null)
break;
else if (line.matches("\\#\\s[a-zA-Z]")){
String key = line.split("\\t")[1];
line = br.readLine();
data.put(key, computeLine(line));
}
else if (line.matches("\\\\\\#\\s(\\|[a-zA-Z]\\|,?\\s?)+")){
String[] keys = line.split("\\t");
line = br.readLine();
ArrayList<Integer> results = computeLine(line);
for (int i=0; i<keys.length; i++){
aKey = aKey.replace("|", "");
// data.put(aKey, results.get(i));
data.put(aKey, results);
}
}
System.out.println(data);
}
} catch(Exception ex) {
ex.printStackTrace(); }
}
private static ArrayList<Integer> computeLine (String line){
String[] splitted = line.split("\\t");
for (String s : splitted) {
integerList.add(Integer.parseInt(s));
}
return integerList;
}
}
And example of the data is seen here:
\# TAP instance
\# Note that the sequence of the data is important!
\#
\# |L|, |T|, |S|
30 38 1
\#
\# v
8213 9319 10187 12144 8206 ...
\#
\# w
7027 9652 9956 13973 6661 14751 ...
\#
\# b
1 1 1 1 1 ...
\#
\# c
1399 1563 1303 1303 2019 ...
\#
\# continues
The following code is working with the sample data you gave.
In short :
Create a field to store your data, I chose a TreeMap so you can map a letter to a certain number of Integers but you can use another Collection.
Read the file line by line using BufferedReader#readLine()
Then process each bunch of lines depending on your data. Here I use regular expressions to match a given line and then to remove everything that is not data. See String#split(), String#matches()
But before all start by reading some good beginners books about java and Object Oriented Design.
public class ReadAndParse {
public Map<String, ArrayList<Integer>> data = new TreeMap<String, ArrayList<Integer>>();
public ReadAndParse() {
try {
FileReader fr = new FileReader("test.txt");
BufferedReader br = new BufferedReader(fr);
while(true) {
String line = br.readLine();
if (line == null) break;
else if (line.matches("\\\\#\\s[a-zA-Z]")){
String key = line.split("\\s")[1];
line = br.readLine();
ArrayList<Integer> value= computeLine(line);
System.out.println("putting key : " + key + " value : " + value);
data.put(key, value);
}
else if (line.matches("\\\\\\#\\s(\\|[a-zA-Z]\\|,?\\s?)+")){
String[] keys = line.split("\\s");
line = br.readLine();
ArrayList<Integer> results = computeLine(line);
for (int i=1; i<keys.length; i++){
keys[i] = keys[i].replace("|", "");
keys[i] = keys[i].replace(",", "");
System.out.println("putting key : " + keys[i] + " value : " + results.get(i-1));
ArrayList<Integer> value= new ArrayList<Integer>();
value.add(results.get(i-1));
data.put(keys[i],value);
}
}
}
}
catch (IOException e) {
e.printStackTrace();
}
// print the data
for (Entry<String, ArrayList<Integer>> entry : data.entrySet()){
System.out.println("variable : " + entry.getKey()+" value : "+ entry.getValue() );
}
}
// the compute line function
private ArrayList<Integer> computeLine(String line){
ArrayList<Integer> integerList = new ArrayList<>();
String[] splitted = line.split("\\s+");
for (String s : splitted) {
System.out.println("Compute Line : "+s);
integerList.add(Integer.parseInt(s));
}
return integerList;
}
// and the main function to call it all
public static void main(String[] args) {
new ReadAndParse();
}
}
Some sample output of what I got after parsing your file :
variable : L value : [30]
variable : S value : [1]
variable : T value : [38]
variable : b value : [1, 1, 1, 1, 1]
variable : c value : [1399, 1563, 1303, 1303, 2019]
variable : v value : [8213, 9319, 10187, 12144, 8206]
variable : w value : [7027, 9652, 9956, 13973, 6661, 14751]
I think I've got something.
EDIT:
I've changed my approach
You'll need to import;
import java.io.BufferedReader;
Then
BufferedReader reader = new BufferedReader
int[] arr = new int[3];
int L;
int T;
int S;
for (int i = 0 ;i<5; i++){ //brings you to fifth line
line = reader.readLine();
}
L = line.split(" ")[0]trim();
T = line.split(" ")[1]trim();
S = line.split(" ")[2]trim();
arr[0] = (L);
arr[1] = (T);
arr[2] = (S);
I have a csv file of all the stock quotes on in the nyse. first column is symbol second column is the name of the company.
I have a search box and table made in netbeans using the java swing library.
Right now when I enter the name in the box it is returning the correct amount of rows. So for instance if I search GOOG it will only return 2 rows (1 row for the GOOG symbol and one row for the name in the full company name). However the data within the rows is not the correct ones it is just printing the first row of the csv file over and over. here is the code that gets executed when clicking the search button:
package my.Stock;
import java.util.ArrayList;
import java.util.Scanner;
import java.io.BufferedReader;
import java.util.StringTokenizer;
import java.io.FileReader;
import java.io.*;
public class searchy {
public static void doSearch(String s){
javax.swing.JTable resTable = StockUI.stockUI.getResultTable();
javax.swing.table.DefaultTableModel dtm =
(javax.swing.table.DefaultTableModel) resTable.getModel();
while (dtm.getRowCount()> 0 ) dtm.removeRow(0);
String sym = s.trim().toUpperCase();
try {
//csv file containing data
String strFile = "companylist.csv";
//create BufferedReader to read csv file
BufferedReader br = new BufferedReader( new FileReader(strFile));
String strLine = "";
StringTokenizer st = null;
int lineNumber = 0, tokenNumber = 0;
//create arraylist
ArrayList<String> arrayList = new ArrayList<String>();
//read comma separated file line by line
while( (strLine = br.readLine()) != null){
lineNumber++;
//break comma separated line using ","
st = new StringTokenizer(strLine, ",");
while(st.hasMoreTokens()){
//display csv values
tokenNumber++;
arrayList.add(st.nextToken());
//System.out.println("Line # " + lineNumber + ": "+ st.nextToken() + " " + st.nextToken());
} //end small while
//reset token number
tokenNumber = 0;
} //end big while loop
//send csv to an array
Object[] elements = arrayList.toArray();
/*
for(int i=0; i < elements.length ; i++) {
System.out.println(elements[i]);
} */
Scanner input = new Scanner(System.in);
System.out.print("Enter Ticker symbol");
//String sym = input.next().toUpperCase(); //convert to uppercase to match csv
int j=0;
for(int i=0; i < elements.length ; i++) {
if (((String) elements[i]).contains(sym)){
//System.out.println(elements[i]);
dtm.addRow(elements);
j++;
if (j==25) break; //only show this many results
}
}
}
catch(Exception e){
System.out.println("Exception while reading csv file: " + e);
}
}
}
I understand why this is happening but I am not sure how to tell it to print the correct lines since I can't use dtm.addRow(elements[i]);
Any help is greatly appreciated.
Try CSVManager.
I collect csv data for stocks from Yahoo, and, oddly enough, every now and then they mess it up by using a company name with a comma in it, e.g., "Dolby, Inc.". Of course, that throws off the parsing of the CSV file. I don't know if this might be your problem.
John Doner
package recommendation.event.test;
import java.io.FileReader;
import com.csvreader.CsvReader;
public class ReadCSV {
public static void main (String [] args){
try {
CsvReader products = new CsvReader("resources/Event Recommendation Engine Challenge/data/test.csv");
products.readHeaders();
while (products.readRecord())
{
String user = products.get("user");
String event = products.get("event");
String invited = products.get("invited");
String timestamp = products.get("timestamp");
System.out.println(user + " : " + event+" : "+invited+" : "+timestamp);
}
products.close();
}catch (Exception e) {
// TODO: handle exception
}
}
}