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
Related
How can I sort a cvs file by one field in Java?
For example I want to sort it by the third field
I have a cvs file that looks like this:
1951,Jones,5
1984,Smith,7
...
I tried using Scanner as such, with a delimiter but I couldn't figure out how to go on:
public static void main(String[] args)
{
//String data = args[0];
Scanner s = null;
String delim = ";";
try
{
s = new Scanner(new BufferedReader (new FileReader("test.csv")));
List<Integer> three = new ArrayList<Integer>();
while(s.hasNext())
{
System.out.println(s.next());
s.useDelimiter(delim);
}
}
catch(FileNotFoundException e)
{
System.out.println("File not found");
}
finally
{
if(s != null)
{
s.close();
}
}
}
Thank you!
public static void main(String[] args)
{
final String DELIM = ";";
final int COLUMN_TO_SORT = 2; //First column = 0; Third column = 2.
List<List<String>> records = new ArrayList<>();
try (Scanner scanner = new Scanner(new File("test.csv"))) {
while (scanner.hasNextLine()) {
records.add(getRecordFromLine(scanner.nextLine(), DELIM));
}
}
catch(FileNotFoundException e){
System.out.println("File not found");
}
Collections.sort(records, new Comparator<List<String>>(){
#Override
public int compare(List<String> row1, List<String> row2){
if(row1.size() > COLUMN_TO_SORT && row2.size() > COLUMN_TO_SORT)
return row1.get(COLUMN_TO_SORT).compareTo(row2.get(COLUMN_TO_SORT));
return 0;
}
});
for (Iterator<List<String>> iterator = records.iterator(); iterator.hasNext(); ) {
System.out.println(iterator.next());
}
}
private static List<String> getRecordFromLine(String row, String delimiter) {
List<String> values = new ArrayList<String>();
try (Scanner rowScanner = new Scanner(row)) {
rowScanner.useDelimiter(delimiter);
while (rowScanner.hasNext()) {
values.add(rowScanner.next());
}
}
return values;
}
** Note that the example file is separated by comma, but in the code you use semicolon as the delimiter.
I'm reading from a text file which looks like this:
1
The Adventures of Tom Sawyer
2
Huckleberry Finn
4
The Sword in the Stone
6
Stuart Little
I have to make it so that the user can enter the reference number and the program will perform binary and linear search and output the title. My teacher said to use two ArrayLists, one for the numbers and one for the titles, and output from them. I just can't figure out how to skip lines so I can add to the corresponding arraylist.
int number = Integer.parseInt(txtInputNumber.getText());
ArrayList <String> books = new ArrayList <>();
ArrayList <Integer> numbers = new ArrayList <> ();
BufferedReader br = null;
try {
br = new BufferedReader(new FileReader("bookList.txt"));
String word;
while ((word = br.readLine()) != null ){
books.add(word);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
br.close();
} catch (IOException ex) {
ex.printStackTrace();
}
}
Thanks in advance, I appreciate any help!
You can check if you are in even or odd lines by doing a modulo 2 operation on the line number:
try (BufferedReader br = new BufferedReader(new FileReader("bookList.txt"))) {
String word;
int lineCount = 0;
while ((word = br.readLine()) != null ){
if (++lineCount % 2 == 0) {
numbers.add(Integer.parseInt(word));
} else {
books.add(word);
}
}
} catch (IOException e) {
e.printStackTrace();
}
int number = Integer.parseInt(txtInputNumber.getText());
ArrayList <String> books = new ArrayList <>();
ArrayList <Integer> numbers = new ArrayList <> ();
BufferedReader br = null;
try {
br = new BufferedReader(new FileReader("bookList.txt"));
String word;
while ((word = br.readLine()) != null ){
numbers.add(Integer.valueOf(word));
word = br.readLine()
books.add(word);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
br.close();
} catch (IOException ex) {
ex.printStackTrace();
}
}
You could make check to see if it is actually a integer, that you read from the file. As far as I remember, there is no built in method to do this, but you can define your own as:
boolean tryParseInt(String value) {
try {
Integer.parseInt(value);
return true;
} catch (NumberFormatException e) {
return false;
}
}
Then just make a check to see if the line you have read in is a integer or not.
int number = Integer.parseInt(txtInputNumber.getText());
ArrayList <String> books = new ArrayList <>();
ArrayList <Integer> numbers = new ArrayList <> ();
BufferedReader br = null;
try {
br = new BufferedReader(new FileReader("bookList.txt"));
String word;
while ((word = br.readLine()) != null ){
if (tryParseInt(word))
numbers.add(Integer.parseInt(word))
else
books.add(word);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
br.close();
} catch (IOException ex) {
ex.printStackTrace();
}
}
Hope this help!
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;
}}
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);
}
I used reverse a string, but now need the final document is the principle, and vice versa:
Hello
Bye
to
Bye
hello
and not:
olleH
eyB
As I do this?
This is my source:
public static void main(String[] args) {
if (args.length != 1) {
System.err.println("Sintaxis incorrecta, introduzca el nombre del fichero");
System.exit(1);
}
BufferedReader br = null;
try {
br = new BufferedReader(new FileReader(args[0]));
String s;
try {
while ((s = br.readLine()) != null) {
StringBuilder reverse = new StringBuilder(s);
String sCadenaInvertida = reverse.reverse().toString();
System.out.println(sCadenaInvertida);
}
} catch (IOException e) {
e.printStackTrace();
}
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
Thanks!!
Just put everything in an ArrayList and use Collections.reverse
http://www.java2s.com/Code/Java/Collections-Data-Structure/ReverseorderofallelementsofJavaArrayList.htm
pseudo code:
ArrayList<String> arrayList = new ArrayList<>();
arrayList.add("Hello");
arrayList.add("Bye");
Collections.reverse(arrayList);
System.out.println(arrayList);
Add the items to an array (first come first serve) then traverse the array in reverse
for (into I = array.length; i >= 0; i--) {
//print array[i]
}
Alternatively you can use an ArrayList if you don't know the number of lines in the document
ArrayList<String> theWords= new ArrayList<String>();
while ((s = br.readLine()) != null) {
//split line into words
String[] parts = s.split("\\s+"):
//for each word append to arraylist
for(String s : parts)
{
theWords.append(s);
} //end for loop
} //end while loop
// iterate array, from size-1 to 0
int theWordsSize = theWords.size()--;
for(int i= theWordsSize; i >= 0; i--)
{
System.out.println(theWords.get(i));
} //end for loop
here the answer, It was easy:
public class Reverse2 {
public static void main(String[] args) {
if(args.length != 1){
System.err.println("Sintaxis incorrecta, introduzca el nombre del fichero");
System.exit(1);
}
BufferedReader br = null;
try {
br = new BufferedReader(new FileReader(args[0]));
ArrayList<String> lista = new ArrayList<String>();
String s;
try {
while((s=br.readLine()) != null){
lista.add(s);
}
for(int i= lista.size()-1;i>=0;i--){
System.out.println(lista.get(i));
}
} catch (IOException e) {
e.printStackTrace();
}
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
}
thanks for all the possible solutions