Use csv data as string java - java

This maybe simple but java isn’t really my thing but I'm working with a java API.
I need to parse a csv file and use the values as strings.
CSV file:
Mac,device,level ,key number,key function ,name,number,prim
01:1A:E8:84:9D:27,0,0,1,31,line,441865945218,TRUE
01:1A:E8:84:9D:27,0,0,2,51,dss,441865985452,FALSE
each row need to be read seprately so something like.
Read first row of csv
Assign values to strings (e.g. mac = 01:1A:E8:84:9D:27 device = 0 and so on)
Run "code" using these strings
Read second row of csv
So on till end of csv.
Thanks
I have tried csvreader but I'm not able to use the strings outside of the while function and it does not read line by line.
CsvReader phones = new CsvReader("dls.csv");
phones.readHeaders();
while (phones.readRecord()){
String deviceID = phones.get("Mac");
String device = phones.get("device");
String level = phones.get("level");
String keynumber = phones.get("key number");
String keyfunction = phones.get("key Function");
String label = phones.get("name");
String e164 = phones.get("number");
String prim = phones.get("prim");
}

As you are new to Java, whatever you are doing, looks like it reads the file line by line. But as you are defining the Strings in while loop, you won't be able to access it outside.
If you want to read all lines and store in Strings, you should probably take array for all of them and define them outside the while loop, add values in the loop and then you'll be able to use it.
Or just create a Phone class:
public class Phone{
String deviceId;
String device;
......etc...
//setters and getters
}
And take an array of it outside while. Something like this:
CsvReader phones = new CsvReader("dls.csv");
phones.readHeaders();
List<Phone> phonesArr=new ArrayList<Phone>();
while (phones.readRecord())
{
Phone phone=new Phone();
phone.setDeviceId(phones.get("Mac"));
phone.setDevice(phones.get("device"));
.....
phones.add(phone);
}
// array phones will be accessible here
Hope that helps!

You have to declare the Strings outside of the loop. Otherwise the String variables would be loop scoped.
CsvReader phones = new CsvReader("dls.csv");
phones.readHeaders();
String deviceID;
String device;
String level;
String keynumber;
String keyfunction;
String label;
String e164;
String prim;
while (phones.readRecord()){
deviceID = phones.get("Mac");
device = phones.get("device");
level = phones.get("level");
keynumber = phones.get("key number");
keyfunction = phones.get("key Function");
label = phones.get("name");
e164 = phones.get("number");
prim = phones.get("prim");
}
See:
Scopes tutorial
Javadoc: Variables

In the end I just called the funtion from the while loop.
while (phones.readRecord()) {
deviceID = phones.get("Mac");
Device = phones.get("device");
Level = phones.get("level");
Keynumber = phones.get("key number");
Keyfunction = phones.get("key function");
Label = phones.get("name");
E164 = phones.get("number");
Prim = phones.get("prim");
tools connect = new tools();
connect.connect();
connect.setkeys(deviceID,Device,Level,Label,Keynumber,Keyfunction,E164,Prim);
//System.out.println(Prim);
}
phones.close();

Related

I want to data type Conversion in a row in android

Hi.
I'm making an app that receives data from bluetooth by using stringbuilder
And makes it slice for using another activity.
The image shows what i want to make.
Q1. What should i use c->d, d->e ?
Q2. There will be a lot of data, I want to know the way to simplify this sequence
******************** edited ********************
I have practiced by adding value to Arraylist.
But in String Array, there is no .get(), so i couldn't access to element's length.
public static ArrayList<String> randomValue = new ArrayList<>();
public static int iDistance=0, xIAngle=0, yIAngle=0, zIAngle=0;
public static String distance, xAngle, yAngle, zAngle;
randomValue.add("12345090080070");
randomValue.add("15640080085071");
randomValue.add("16542070084074");
randomValue.add("12645080087078");
randomValue.add("21345084081060");
randomValue.add("14785078075065");
randomValue.add("13155079077077");
randomValue.add("14623080078078");
randomValue.add("14918086080078");
randomValue.add("15684085082080");
for (int i=0; i<randomValue.size(); i++){
String a = randomValue.get(i);
String distance = a.substring(0,5);
String xAngle = a.substring(5,8);
String yAngle = a.substring(8,11);
String zAngle = a.substring(11,14);
//String to int
iDistance = Integer.parseInt(distance);
xIAngle = Integer.parseInt(xAngle);
yIAngle = Integer.parseInt(yAngle);
zIAngle = Integer.parseInt(zAngle);
}
It seems like you are just stuck on finding the equivalent of get for a string array. To access an element in an array, the syntax is array[I], so if you were using a string array, this line:
String a = randomValue.get(i);
would have been:
String a = randomValue[i];
The code for your sequence of transformations can be shortened with Streams:
// this is the sequence of transformation starting with the sting builder "a"
List<String> randomValueWithLength14 =
Arrays.stream(a.toString().split(";")).filter(x -> x.length() == 14)
.collect(Collectors.toList());
// this is the for loop shown in your code
for (int i=0; i<randomValueWithLength14.size(); i++){
String s = randomValueWithLength14.get(i);
String distance = a.substring(0,5);
String xAngle = s.substring(5,8);
String yAngle = s.substring(8,11);
String zAngle = s.substring(11,14);
//String to int
iDistance = Integer.parseInt(distance);
xIAngle = Integer.parseInt(xAngle);
yIAngle = Integer.parseInt(yAngle);
zIAngle = Integer.parseInt(zAngle);
}

Android read text file and store into variable based on first word

I am doing a reading text file practice where I read and store the data into a string array object. One ArrayList data should have photo, title, website, and date. The text file looks like this:
photo:android_pie
title:Android Pie: Everything you need to know about Android 9
website:https://www.androidcentral.com/pie
date:20-08-2018
photo:oppo
title:OPPO Find X display
website:https://www.androidpit.com/oppo-find-x-display-review
date:25-08-2018
photo:android_pie2
title:Android 9 Pie: What Are App Actions & How To Use Them
website:https://www.androidheadlines.com/2018/08/android-9-pie-what-are-app-
actions-how-to-use-them.html
date:16-09-2018
I am trying to split and store them into a string array, which is an instance of my object class:
private List<ItemObjects> itemList;
and this is the constructor of my object class:
public ItemObjects(String photo, String name, String link, String date) {
this.photo = photo;
this.name = name;
this.link = link;
this.date = date;
}
I tried this but the ":" separator doesnt separate it like I want it to:
while ((sItems = bufferedReader.readLine()) != null) {
if (!sItems.equals("")) {
String[] tmpItemArr = sItems.split("\\:");
listViewItems.add(new ItemObjects(tmpItemArr[0], tmpItemArr[1], tmpItemArr[2], tmpItemArr[3]));
}
}
What is the best way of doing this? I have tried using for loop which stops at third line and adds the next one as new data. There are several online ways of doing it but some are very complicated and I am having trouble understanding it.
The problem is your understanding of using both the split function and the BufferReader.
By using readline function you are reading only one line so your split will split the first line only, you need to read the 4 first lines then add the item.
int count = 0;
String[] tmpItemArr = new String[4];
while ((sItems = bufferedReader.readLine()) != null) {
if (!sItems.equals("")) {
tmpItemArr[count] = sItems.split(":")[1];
count++;
if (count > 3) {
listViewItems.add(new ItemObjects(tmpItemArr[0], tmpItemArr[1], tmpItemArr[2], tmpItemArr[3]));
count = 0;
}
}
}

How to compare array elements that are not parrallel while looping through the lines of a text file?

I am stuck with this logic. I have two text files that the program reads, but I cannot get it to compare each other the following way:
First text file looks like this:
1,01/04/14,apo,14:47:53,
2,01/04/14,apo,14:48:08,
3,01/04/14,apo,14:48:25,
7,01/04/14,apo,14:53:50,
Second text file looks like this:
1,01/04/14,apo,14:47:53,
2,01/04/14,apo,14:48:08,
4,01/04/14,apo,14:48:25,
7,01/04/14,apo,14:53:50,
Each line of text from each file is stored in an array. I want to grab from the first line of the first text file, the first array of the first line which is "1" and compare that to every first array element of each line in the second file. Then grab the first array element of the second line of the first text file which is "2" and compare that to the first array element of each line on the second text file.
This is what I have done so far:
while ( (tkp = tkpbr.readLine()) != null && (tkn = tknbr.readLine()) != null){
tkparray = tkp.split(",");
int c = 0;
for(String s : tkparray){
//System.out.println("values[" + c + "] = " + s);
c++;
}
tknarray = tkn.split(",");
int a = 0;
for(String s : tknarray){
//System.out.println("values[" + a + "] = " + s);
a++;
}
if(tkparray[0].contentEquals(tknarray[0])){
System.out.println(tkparray[0]+"\t"+tknarray[0]);
}
}
This works, but if the array elements are not equal or if the text files look like below it won`t work:
First text file looks like this:
1,01/04/14,apo,14:47:53,
2,01/04/14,apo,14:48:08,
3,01/04/14,apo,14:48:25,
7,01/04/14,apo,14:53:50,
Second text file looks like this:
3,01/04/14,apo,14:47:53,
7,01/04/14,apo,14:48:08,
1,01/04/14,apo,14:48:25,
2,01/04/14,apo,14:53:50,
Any help is greatly appreciated!
There are several ways of doing it.
One is to create a class that modelizes each lines of both files. Assuming each line is unique in a file (looking at the first number), store each lines in two Set and check for equality at the end.
class Date {
private long id;
private Date date;
private String desc;
//constructor and all stuff
//don't forget to override equals and hashcode
}
Set<Data> datasFileOne = new HashSet<>();
Set<Data> datasFileTwo = new HashSet<>();
SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss");
while ((tkp = tkpbr.readLine()) != null && (tkn = tknbr.readLine()) != null){
tkparray = tkp.split(",");
datasFileOne.add(new Data(Long.parseLong(tkparray[0]),
sdf.format(tkparray[1]+" "+tkparray[3]),
tkparray[2]);
//do the same thing for setFileTwo
}
boolean filesEquals = datasFileOne.equals(datasFileTwo);
If you don't care about storing those values in a POJO, you could use Files.readAllLines (if you're using Java 7).
Path p1 = //Path to file one
Path p2 = //Path to file two
Charset cs = //encoding of the files
List<String> datasFileOne = Files.readAllLines(p1, cs);
List<String> datasFileTwo = Files.readAllLines(p2, cs);
if(datasFileOne.size() == datasFileTwo.size()){
Collections.sort(datasFileOne);
Collections.sort(datasFileTwo);
if(datasFileOne.equals(datasFileTwo)){
//same content
}
} else {
//not same content
}

How to replace words with Parallel arrays

Hello i am new to this forum. I am fairly new to Java. I am trying to convert USA to UK words so that when i input a sentence containing any of the USA words, the output will be will be the sentence but replaced with UK words. This is my attempt:
import javax.swing.JOptionPane;
public class PArraystest
{
public static void main(String [] arg)
{
String[] wordUSA = {"Cell", "Elevator", "Fries", "Gasoline", "Faucet"};
String[] wordUK = {"Mobile", "Lift", "Chips", "Petrol", "Tap"};
String changeUK = "";
String sent;
sent = JOptionPane.showInputDialog("What name do you want to search for?");
for (int i = 0; i < wordUSA.length; i++)
{
if (sent.contains(wordUSA[i]))
{
sent.replace((wordUK)[i],(wordUSA)[i]);
//break;
}
}
//if (changeUK.equals(""))
//System.out.println(" was not found.");
//else
System.out.println(sent);
}
}
Two things:
You need to use assign the string returned from replace to sent again, or sent will be unchanged`.
The replace method is public String replace(char oldChar, char newChar), so the oldChar US word should come first, followed by the UK word.
This is the correct line: sent = sent.replace(wordUSA[i],wordUK[i]);
The replace method returns a new String with the replaced text:
//sent.replace((wordUK)[i],(wordUSA)[i]);
sent = sent.replace((wordUK)[i],(wordUSA)[i]);
Two problems:
First, you should assign the replaced string back to sent.
Second, you should use replaceAll instead of replace.
There's a whole framework of functionality devoted to this in Java called internationalizaion (i18n)
While the sample below is primarily for generation origianlly I thought I'd point it out because you could probably devise how to run it in reverse as well.
Here's a snippet that shows the proper way to go about this:
http://docs.oracle.com/javase/tutorial/i18n/intro/after.html
(all code below is theirs and not my own)
Note that to run this you'll need the resource files from the site or the versions I have provided below from the site
import java.util.*;
public class I18NSample {
static public void main(String[] args) {
String language;
String country;
if (args.length != 2) {
language = new String("en");
country = new String("US");
} else {
language = new String(args[0]);
country = new String(args[1]);
}
Locale currentLocale;
ResourceBundle messages;
currentLocale = new Locale(language, country);
messages = ResourceBundle.getBundle("MessagesBundle", currentLocale);
System.out.println(messages.getString("greetings"));
System.out.println(messages.getString("inquiry"));
System.out.println(messages.getString("farewell"));
}
}
MessagesBundle.properties:
greetings = Hello.
farewell = Goodbye.
inquiry = How are you?
MessagesBundle_en_US.properties:
greetings = Hello.
farewell = Goodbye.
inquiry = How are you?
MessagesBundle_fr_FR.properties:
greetings = Bonjour.
farewell = Au revoir.
inquiry = Comment allez-vous?

Randomizing in Java

I have 4 Strings to represent people and 4 Strings to represent names.
I'm trying to randomize them so that every time I start my application, my four people will have different names, but no one can have the same name during runtime.
Example:
String person_one;
String person_two;
String person_three;
String person_four;
String name_one = "Bob";
String name_two = "Jane";
String name_three = "Tim";
String name_four = "Sara";
Hope this makes some sense.
You can use Collections.shuffle():
List<String> names = new ArrayList<String>();
names.add("Bob");
names.add("Jane");
names.add("Tim");
names.add("Sara");
Collections.shuffle(names);
person_one = names.get(0);
person_two = names.get(1);
person_three = names.get(2);
person_four = names.get(3);
You can use Collections.shuffle().

Categories

Resources