String split from a CSV - Java - java

I am having a small problem, I hope you can help.
I am reading a CSV in java, in which one of the column has string as follows:
a. "123345"
b. "12345 - 67890"
I want to split this like(Split it into two separate columns):
a. "123345", ""
b. "12345","67890"
Now, when I am using Java's default split function, it splits the string as follows:
a. "123345,"
b. "12345,67890" (Which is basically a string)
Any idea how can I achieve this? I have wasted my 3 hours on this. Hope any one can help.
Code as follows:
while ((line = bufferReader.readLine()) != null)
{
main = line.split("\\,"); //splitting the CSV using ","
//I know that column # 13 is the column where I can find digits like "123-123" etc..
therefore I have hard coded it.
if (main[12].contains("-"))
{
temp = main[12].split("-");
//At this point, when I print temp, it still shows me a string.
//What I have to do is to write them to the csv file.
E.g: ["86409, 3567"] <--Problem here!
}
else
{
//do nothing
}
}
after this, i will write the main[] array to the file.

Please check if java.util.StringTokenizer helps
Example:
StringTokenizer tokenizer = new StringTokenizer(inputString, ";")
Manual: StringTokenizer docs

Related

How can I fix my code to find a certain character in an array and make changes to that array

while (scan_file.hasNext()) {
String b = scan_file.nextLine();
// checks if string b contains the tag <h>
if (b.contains("<h>")) {
char arrayString[] = b.toCharArray();
for (int i = 0; i < arrayString.length; i++) {
if (arrayString[i] == '<') {
arrayString[i] = arrayString[i + 2];
}
System.out.print(arrayString[i]);
}
}
}
What I was expecting the program to do was(for now) iterate through the while loop and store each line as string 'b'.
I want to check if that string b contains a certain string like <h> for this example. And I want to convert string b into an array if it contains said string like <h> and iterate through that array to check for '<' and move the array up 2 spaces.
For example, string b had <h>hello, I wanted to eventually print hello because the program would have moved up 2 elements.
I feel like I got the loops and general idea on how I want to tackle the problem.. but when I ran the program, nothing printed so I don't know if I did the loops and if statements correctly.
I really don't know how to word my problem well, so bear with me and I'm sorry in advance.
All feedbacks are greatly appreciated (:
System.out.print(arrayString[i]); just print the ith character of arrayString, it's definitely not what you want.
In fact you don't have to convert a String to char[], String has many utils method can help you with your goal.
I won't give you full code , but I can give you some tips.
You can use String.indexof('<') to find the index of '<'.
You can use String.subString(startIndex) to get the subString start with the specified index.
Suppose your code scan_file.hasNext() and scan_file.nextLine() is work well. You can try code below to remove all from current line:
if (b != null && b.contains("<h>")) {
System.out.println(b.replaceAll("<h>", ""));
}

In Java, how do I read both Strings and Doubles from the same txt file? [duplicate]

I am creating a simple program to data read from a text file. The file stores information about a person, with the name, age and a number on each line:
Eg: File format per line
Francis Bacon 50 2
I can read in a file no problem if it is just text, but I am confused on how to differentiate between text and numbers. Here is a look at my code:
import java.io.*;
public class Test{
private People people[] = new People[5];
public Test(){
BufferedReader input;
input = new BufferedReader(new FileReader("People.txt"));// file to be readfrom
String fileLine;
int i = 0;
while (test != null){
fileLine = input.readLine();
// Confused as to how to parse this line into seperate parts and store in object:
// eg:
people[i].addName(fileLine - part 1);
people[i].addBookNo(fileLine - part 2);
people[i].addRating(fileLine - part 3)
i++
}
}
}
I strongly suggest you use the Scanner class instead. That class provides you with methods such as nextInt and so on.
You could use it to read from the file directly like this:
Scanner s = new Scanner(new File("People.txt"));
while (s.hasNext()) {
people[i].addName(s.next());
people[i].addBookNo(s.nextInt());
people[i].addRating(s.nextInt());
}
(Just realized that you may have spaces in the name. That complicates things slightly, but I would still consider using a scanner.)
An alternative solution would be to use a regular expression and groups to parse the parts. Something like this should do:
(.*?)\s+(\d+)\s+(\d+)
The following regex works on these 3 cases, breaking them into 3 matched groups.
Regex
(.*)\s+(\d+)\s+(\d+)
Cases
Francis Bacon 50 2
Jill St. John 20 20
St. Francis Xavier III 3 3
If you want to do in this way, you can try doing like this :
Fixing the way data will be present in the file, say
firstName.lastName.age.number;
Then you can write code to read data upto . and store it in a variable (you will be knowing what it is meant for) and after ";" there will be second entry.

java check a given string in csv file

I have a csv file the format is like this:
I have a another csv file which is the same number of columns and rows.
I need to check if file 1 has same value (value[0]) as file 2 and if not copy value from file 2.
Below is the code I have written, but when checking, if file 1 first row value is not equal to the row, I need to go and check the next row of file 2 without exiting the if statement.
while ((line = br4.readLine()) != null){
while ((line5 = br5.readLine()) != null){
String[] values = line.split(",");
String[] values5 = line5.split(",");
fw5.append("0").append('\n');
String comp2 = values[0];
String comp1 = values5[0];
if (values5[0] == null ? values[0] == null : values5[0].equals(values[0]))
{
fw6.append(values[0]).append("mad men ").append('\n');
}
else if ( values5[0] == null ? (values[0]) != null : !values5[0].equals(values[0])){
System.out.println("value is " +values5[0]);
fw6.append(values5[0]).append("mad women").append('\n');
fw6.flush();
}
break;
}
}
You are facing a typical newbie problem: insufficient abstractions.
You try to solve your whole problem in one method: instead create helpful abstractions. Like this:
first you create a class representing that row data. You might pass a string (content of one row) to the constructor. Then that class splits the string and puts all entries into meaningful named fields (instead of using an array named values which does not say anything).
then you add methods to that class to compare two instances of the class (could be the equals method or something you define on your own).
and while doing all of that you keep testing the code as you write.
then when you can parse that line of text and compare it as desired - then you add the code to read lines from your files. You read all lines, create objects and update them as required.
and finally you write code that writes updated objects back into file.
Long story short: slice your big problem into smaller ones and solve them one after the other.

Finding a word and copying the line it's in in Java

I'm trying to create a small program that allows you to search for a word in a text file, and then the program should print out the whole line the text is in.
Example:
test.txt
don't mind this text
don't mind this either
and then when you let the program search for the word "text", it should print out "Don't mind this text".
What's the best way to do this?
This is what I have;
public boolean findFileInCache(){
try (BufferedReader br = new BufferedReader(new FileReader("direct.txt")))
{
while ((name = br.readLine()) != null)
{
Process p = Runtime.getRuntime().exec(name);
}
}
catch (IOException e1) { }
return true;
}
Use BufferedReader to read the file line by line using the BufferedReader.readLine() method.
For each line, check if the word is in it using a regular expression, or by splitting the line into a String[] (using String.split()), and iterating the entries in the resulting array to check if any of them is the desired word. If the desired word is there - print the entire line.
If you chose the 2nd suggestion, don't forget to check equality of two strings by using equals() and NOT by using ==
There are a couple of things you need to do:
Learn the basics by going through an introductory Java book, or course notes, from the beginning, making sure you understand each step as it comes.
Read the Javadocs of likely classes, to find methods that could be useful for the task.
You have already found two core pieces of the solution:
You are getting a line at a time using BufferedReader.readLine()
You are doing it in a while loop, so you handle one line at a time
Now, you need to work out how to deal with each line. Although you didn't include the type, name is a String. It would be better as:
while ((String name = br.readLine()) != null) {
... do something with `line`
}
If your code compiled without String there, it means you declared name as a global. Don't do that, until you know what you're doing.
Breaking things into methods is good; so let's make "do something with line" use a method now:
while ((String name = br.readLine()) != null) {
if(matches(line,"text")) {
System.out.println(line);
}
}
Now you need to write matches():
private boolean matches(String line, String word) {
boolean result = // work out whether it's a match
return result;
}
So, how do you write the guts of matches()?
Well, start by looking at the methods available in String. It has methods like contains() and split(). Some of those methods return other types, like arrays. Your teaching material and reference materials tell you how to look in arrays. The answers are there.

How to read a string with spaces in Java

I am trying to read a user input string which must contain spaces. Right now I'm using:
check = in.nextLine();
position = name.names.indexOf(check);
if (position != -1) {
name.names.get(position);
} else {
System.out.println("Name does not exist");
}
this just returns various errors.
your question isn't very clear - specfically you like like you are checking that what the person has typed matches a known list, not that it does or doesn't have spaces in it, but taking you at your word:
Read the whole line in, then check using
a) Regex
b) indexof() - if your check is very simple
Possibly also want to do a length check on the input line as well (i.e all lines should be < 255 chars or something) , just to be paranoid
If you are doing more like what you code sample looks like then you do something like
ArrayList<String> KnownListOfNames = .....
if(!KnownListOfNames.Contains(UserEnteredString)){
System.out.println("Name not found");
}
Typically you would also do some basic input validation first - google for "SQL injection" if you want to know more.

Categories

Resources