Problems reading text file data in Java - java

I have this code:
BufferedReader br =new BufferedReader(new FileReader("userdetails.txt"));
String str;
ArrayList<String> stringList = new ArrayList<String>();
while ((str=br.readLine())!=null){
String datavalue [] = str.split(",");
String category = datavalue[0];
String value = datavalue[1];
stringList.add(category);
stringList.add(value);
}
br.close();
it works when the variables category and value do not have a comma(,),however the values in the variable value does contain commas.Is there a way that I can split the index of the without using comma?

The solution is given bellow:
BufferedReader br =new BufferedReader(new FileReader("userdetails.txt"));
String str;
ArrayList<String> stringList = new ArrayList<String>();
while ((str=br.readLine())!=null){
int firstIndexOfComma = str.indexOf(',');
String category = str.substring(0, firstIndexOfComma);
String value = str.substring(firstIndexOfComma + 1);
stringList.add(category);
stringList.add(value);
System.out.println(category+" "+value);
}
br.close();

When data has ',' it is generally called CSV file. OpenCSV is fairly used library to handle it. The format looks simple, but it has it quirks. See wikipedia for some details

If I understood you correctly:
String str = "category,vvvv,vvv";
int i = str.indexOf(',');
String category = str.substring(0, i);
String value = str.substring(i + 1);

split() uses regex.
if the reader code works perfectly, do
str.split("\\,");

Not 100% sure, but couldnt you just do
String datavalue [] = str.split("--");
or something?
sample file:
x,y,z--123--Hello World
output:
"x,y,z",
"123",
"Hello World"

Related

Creating email addresses from names in a text file

I've got a text file with a name (first+family name) on every line, from these names I want to create email addresses (in this format : firstname.familyname#address.com.).
My plan is to do something like this:
Make an array with a string for every line in the text file
Split every string in two parts: first name, family name. Where the first name is the first word in the string and the family name is every other word.
Make a new array (splitNameN) for every string (N total strings) with two elements: first name, family name
From each splitNameN array, create a new string: "first name" + "." +"family name"+"#mail.com"
Add all these strings together seperated by a comma (eg: barrack.obama#mail.com;donald.trump#mail.com)
The main thing I dont know how to do is splitting the names and putting them into correct arrays, I can split them but then they lose their grouping.
public static void main(String[] args) throws IOException
{
File file = new File("D:\\NetbeansProjects\\Emails\\src\\emails\\lijst.txt");
BufferedReader abc = new BufferedReader(new FileReader(file));
List<String> data = new ArrayList<String>();
String s;
while((s=abc.readLine())!=null) {
data.add(s);
}
abc.close();
System.out.println(data);
List<String> splitdata = new ArrayList<String>();
for(String strLine : data) {
String[] strWord = strLine.split("[\\s']");
for (String c : strWord) {
splitdata.add(c);
}
}
System.out.println(splitdata);
}
After reading data you can create an 2d array and store first and last name there and then concatenate them to create an email address as you asked for.
String[][] splitdata = new String[data.size()][2];
int rowNum = 0;
for (String strLine : data) {
String[] strWord = strLine.split("[\\s]");
// Store it in an array as you asked for or join them right here
splitdata[rowNum][0] = strWord[0];
splitdata[rowNum][1] = strWord[1];
++rowNum;
}
for (String[] row: splitdata) {
System.out.println(row[0] + "." + row[1] + "#mail.com");
}
If you are using java8 the whole thing as be written as..
Path path = Paths.get("D:\\NetbeansProjects\\Emails\\src\\emails\\lijst.txt");
String commaJoinedEmails = String.join(",", Files.lines(path)
.map(line -> line.split("\\s"))
.map(tokens -> tokens[0] + "." + tokens[1] + "#mail.com")
.toArray(String[]::new));
I would suggest you to read the file line by line.
try (BufferedReader br = new BufferedReader(new FileReader(file))) {
String line;
while ((line = br.readLine()) != null) {
// process the line.
}
This is the most common way of doing it. In the current line parameter you will store the first and family names and after that you can process the two names (preferably with a StringBuffer) and add the result to the final string of your choice.
Good luck :)
You are missing a part in your loop from your explication your lines is like :
firstname1 familyname1
firstname2 familyname2
So after you split you can easily use :
for (String strLine : data) {
String[] strWord = strLine.split("[\\s']");
splitdata.add(strWord[0] + "." + strWord[1] + "#mail.com");
//------------first name last name
}
System.out.println(splitdata);
Output :
[firstname1.familyname1#mail.com, firstname2.familyname2#mail.com]
Note you have to verify your names before you use them, what if the name have many parts, also you have to use the right delimiter between the names.

Java parse a Sting with letters and numbers for an Integer

I'm working with data that is a String followed by spaces and then a numeric value.
ncols 10812
nrows 10812
xllcorner -107.0005555556
yllcorner 36.99944444444
cellsize 9.2592592593e-05
I'm trying to just read in just the numeric value. I know that from going to String to Integer or Double I can use the standard type conversions.
Integer.valueOf(stringOfInteger);
Double.valueOf(stringOfDouble);
In order to get just the numeric value I tried this as a test:
BufferedReader br = new BufferedReader(new FileReader(path));
String line = br.readLine();
line.replace("[a-z]","");
line.replace(" ","");
System.out.println(line);
and it output ncols 10812
I'm also worried about reading the cellsize value as it has an exponential.
You can do this for each line:
...
String[] fields = line.split("\\s+");
String name = fields[0];
float value = Float.parseFloat(fields[1]);
...
This code will split each line in fields using the spaces as a separator. The first field is a String so you can use it directly (or ignore it). The second one is a Float value so you have to convert it before using it. You can use Double if you prefer.
Try this one
BufferedReader br = new BufferedReader(new FileReader(path));
String line = null;
while ((line = br.readLine()) != null) {
// split each line based on spaces
String[] words = line.split("\\s+");
//first word is name
String name = words[0];
// next word is actual number
Double value = Double.valueOf(words[1]);
System.out.println(name + ":" + value);
}
// don't forget to close the stream
br.close();
Output:
ncols:10812.0
nrows:10812.0
xllcorner:-107.0005555556
yllcorner:36.99944444444
cellsize:9.2592592593E-5
If all you want all the numeric values do a split on the space and the second item will contain your numeric value. Then you can do any conversions as needed and not have to worry about removing any exponents.
String[] data = new line.split(" ");
//remove all the spaces from the second array for your data
data[1] = data[1].replaceAll("\\s", "");
//parse to whatever you need data[1] to be
You could use the split function in Java as follows:
String [] dataArr = data.split("[ \t]+"); //assumes #data is you data string variable name
The dataArr, then, will look like this:
dataArr[0] = "ncols"
dataArr[1] = "10812"
dataArr[2] = "nrows"
dataArr[3] = "10812"
.
.
.
dataArr[n - 1] = "9.2592592593e-05" // #n is the size of the array
You could, then, use the Integer.parseInt(String str) to parse your numerical data into integers.

Java Scanner multiple delimiter

I know this is a very asked question but I can't find and apropiate answer for my problem. Thing is I have to program and aplication that reads from a .TXT file like this
Real:Atelti
Alcorcon:getafe
Barcelona:Sporting
My question is how what can I do to tell Java that I want String before : in one ArrayList and Strings after : in another ArrayList?? I guess It's using delimeter method but I don't know how use it in this case.
Sorry for my poor english, I've to improve It i guess. Thanks
use split function of java.
steps:
Declare two arrayList. l1 and l2;
read each line.
split each line by ":", this will return a array of length 2, array. (as per your input)
l1.add(array[0]) , l2.add(array1)
try yourself, post code if you need help :)
check here for use of split function, though through google you can find many different example
Split the string using ":" as delimiter. Add the odd entries from the result to one list and even to another list.
If your text is like this:
Real:Atelti
Alcorcon:getafe
Barcelona:Sporting
You can achieve what you want by using:
StringBuilder text = new StringBuilder();
Scanner scanner = new Scanner(new FileInputStream(fFileName), encoding); //try utf8 or utf-8 for 'encoding'
try {
while (scanner.hasNextLine()){
String line = scanner.nextLine();
String before = line.split(":")[0];
String after = line.split(":")[1];
//dsw 'before' and 'after' - add them to lists.
}
}
finally{
scanner.close();
}
Scanner scanner = new Scanner(new FileInputStream("YOUR_FILE_PATH"));
List<String> firstList = new ArrayList<String>();
List<String> secondList = new ArrayList<String>();
while(scanner.hasNextLine()) {
String currentLine = scanner.nextLine();
String[] tokenizedString = currentLine.split(":");
firstList.add(tokenizedString[0]);
secondList.add(tokenizedString[1]);
}
scanner.close();
Enumerating firstList and secondList will get you the desired result.
1. Use ":" as delimiter.
2. Then Store them in the String[] using split() function.
3. Try using BufferedReader instead of Scanner.
Eg:
File f = new File("d:\\Mytext.txt");
FileReader fr = new FileReader(f);
BufferedReader br = new BufferedReader(fr);
ArrayList<String> s1 = new ArrayList<String>();
ArrayList<String> s2 = new ArrayList<String>();
while ((br.readLine())!=null){
String line = br.readLine();
String bf = line.split(":")[0];
String af = line.split(":")[1];
s1.add(bf);
s2.add(af);
}

How to Split a String to remove certain Parts

I have a File that COntains Strings in This Format:
ACHMU)][2:s,161,(ACH Payment Sys Menus - Online Services)][3:c,1,(M)][4:c,1,(N)]
ACLSICZ)][2:s,161,(Report for Auto Closure)][3:c,1,(U)][4:c,1,(N)]
ACMPS)][2:s,161,(Account Maintenance-Pre-shipment Account)][3:c,1,(U)][4:c,1,(N)]
ACNPAINT)][2:s,161,(Interest Run For NPA Accounts)][3:c,1,(U)][4:c,1,(N)]
I need to Split the String so that I have the data in this Format:
ACHMU (ACH Payment Sys Menus - Online Services)
ACLSICZ (Report for Auto Closure)......
Basically, I want to remove the ")[2:s,161," part and the "][3:c,1,(M)][4:c,1,(N)]" at the end. Will Splitting the String Help Me? The following Method has already failed:
FileInputStream fs = new FileInputStream(C:/Test.txt);
BufferedReader br = new BufferedReader(new InputStreamReader(fs));
String str;
while((str = br.readLine()) != null){
String[] split = str.Split(")[2:s,161,")
}
Please Help me get the Junk in the middle and at the end.
The straight-forward way, use substring() and indexOf():
String oldString = "ACHMU)][2:s,161,(ACH Payment Sys Menus - Online Services)][3:c,1,(M)][4:c,1,(N)]";
String firstPart = oldString.substring(0, oldString.indexOf(")")); // ACHMU
String secondPart = oldString.substring(oldString.indexOf("(")); // (ACH Payment Sys Menus - Online Services)][3:c,1,(M)]
String newString = firstPart + " " + secondPart.substring(0, secondPart.indexOf(")") + 1); // ACHMU (ACH Payment Sys Menus - Online Services)
System.out.print(newString);
OUTPUT:
ACHMU (ACH Payment Sys Menus - Online Services)
You can use
str.replaceFirst("(.*?)\\)\\].*?(\\(.*?\\))\\].*", "$1 $2");
FileInputStream fs = new FileInputStream(C:/Test.txt);
BufferedReader br = new BufferedReader(new InputStreamReader(fs));
String str;
String newStr;
String completeNewStr="";
while((str = br.readLine()) != null)
{
newStr = str.replace(")][2:s,161,"," ");
newStr = str.replace("][3:c,1,(M)][4:c,1,(N)]","");
completeNewStr+=newStr;
}
// completeNewStr is your final string
If the string that you want to replace is always "[2:s,161," , replace it with a empty string or space if that's acceptable. Similarly, for the other string as well.
str.replace("[2:s,161,", '');

how to print part of a string in Java

CODE:
InputStreamReader reader = new InputStreamReader(System.in);
BufferedReader in = new BufferedReader(reader);
String input = in.readLine();
ArrayList<String> massiiv = new ArrayList();
for (int i = 0; i < input.length(); i++)
massiiv.add(input[i]); // error here
HI!
How can I split the input and add the input to the data structure massiiv?
For instance, input is: "Where do you live?". Then the massiiv show be:
massiv[0] = where
massiv[1] = do
massiv[2] = you
THANKS!
The Java Documentation is your friend:
http://download.oracle.com/javase/6/docs/api/java/lang/String.html
String[] myWords = input.split(" ");
InputStreamReader reader = new InputStreamReader(System.in);
BufferedReader in = new BufferedReader(reader);
String input = in.readLine();
String[] massiiv = input.split(" ");
Use a StringTokenizer, which allows an application to break a string into tokens.
Use space as delimiter, set the returnDelims flag to false such that space only serves to separate tokens. Then
StringTokenizer st = new StringTokenizer("this is a test");
while (st.hasMoreTokens()) {
System.out.println(st.nextToken());
}
prints the following output:
this
is
a
test
Try using split(String regex).
String[] inputs = in.readLine().split(" "); //split string into array
ArrayList<String> massiiv = new ArrayList();
for (String input : inputs) {
massiiv.add(inputs);
}
You would use the string.split() method in java. In your case, you want to split on spaces in the string, so your code would be:
massiiv = new ArrayList(input.split(" "));
If you don't want to have the word you in your output, you would have to do additional processing.
A one-line solution. Any amount of whitespace possible between the strings.
ArrayList<String> massiiv = new ArrayList(Arrays.asList(input.split("\\s+")));

Categories

Resources