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,", '');
Related
I have the following code
InputStream inputStream = sock.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
String line = null;
while((line = reader.readLine()) != null) {
String[] data = line.split("\\s+");
//rest of the code
The sender is supposed to send the following String
String DataToSend = "Name John City NewYork \t\t"
What I want is confirm the message coming from client to server ends with double tab \t\t, it doesn't show in the String[] data.
First of all, you need to understand these 2 things:
reader.readLine() will give you string without the newline,
because it reads until newline.
line.split("\\s+") will give you string(s) without whitespace characters, because it splits based on the whitespace characters.
\t, \n, \r, space, are all whitespace characters.
Now, depends on what you want, there are few things that you can do:
check \t\t at the end of each line
You can check before splitting the strings, sample code:
InputStream inputStream = new ByteArrayInputStream("hello\t\t".getBytes());
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
String line = null;
while ((line = reader.readLine()) != null) {
if (line.endsWith("\t\t")) { // check if it ends with \t\t
// do something
}
String[] data = line.split("\\s+");
}
Note: when the \t\t is in the middle of the string e.g. hello\t\tworld, it will not be handled.
read strings until \t\t
You can use Scanner and set \t\t as the delimiter, sample code:
InputStream inputStream = new ByteArrayInputStream("hello\t\tworld\nit's me".getBytes());
Scanner scanner = new Scanner(inputStream);
scanner.useDelimiter("\t\t");
int count = 1;
while (scanner.hasNext()) {
String data = scanner.next();
System.out.println("data number " + count + ":");
System.out.println(data);
System.out.println();
count++;
}
Output:
data number 1:
hello
data number 2:
world
it's me
I want to create an array of objects per each contestant by using the data stored in a text file which includes the details of the 20 contestants. The project is created in IntelliJ and is a Java Project.
The Text File Looks like this ;
Tom Solesbury ;Molesey BC ;26 ;01:29.4 ;02:58.7 ;04:28.0 ;05:58.3
Marcus Bateman ;Leander Club ;24 ;01:28.9 ;02:58.9 ;04:29.2 ;05:58.2
Evgeni Trofimov ;Marine Technical Uni Russia ;35 ;01:28.2 ;03:01.3
;04:34.5 ;06:02.0
String filePath = "birc.txt";
String line ;
BufferedReader reader = new BufferedReader(new FileReader(filePath));
while ((line = reader.readLine()) != null) {
String[] parts = line.split(";", 7);
name = parts[0];
club = parts[1];
age = Integer.parseInt(parts[2]);
fiveHundred = Time.valueOf(parts[3]);
thousand = Time.valueOf(parts[4]);
thousandFiveHundred = Time.valueOf(parts[5]);
twoThousand = Time.valueOf(parts[6]);
Rower rower;
rower = new Rower();
rower.setName(name);
rower.setClub(club);
rower.setAge(age);
rower.setFiveHundred(fiveHundred);
rower.setThousand(thousand);
rower.setThousandFiveHundred(thousandFiveHundred);
rower.setTwoThousand(twoThousand);
rowerDetails[next[0]++] = rower;
}
reader.close();
this here is not correct:
String line = "";
String[] split = line.split(";");
name = split[0];
club = split[1];
since line is an empty string, split will be init with an empty array.
reading the 1st element or second will cause an exception
I am currently codding a Java application for me and my friends and I am encoutering a big problem...
When I try to read a txt file, it prints the lines with strange caracters and each caracter is separed by a white space.
I tryed with multiple txt files in different folders and I prints the same thing everytime... (I tryed to make the code with a Scanner and a BufferedReader and it is still the same problem
Here is my code:
BufferedReader br = new BufferedReader(new FileReader(_file));
String website = "";
String username = "";
String password = "";
int usedTimes = 0;
String currentLine;
while ((currentLine = br.readLine()) != null) {
if(currentLine.startsWith("Web Site")) website = currentLine.split(":")[1];
else if(currentLine.startsWith("User Name")) username = currentLine.split(":")[1];
else if(currentLine.startsWith("Password")) password = currentLine.split(":")[1];
else if(currentLine.startsWith("Password Use Count"))
{
usedTimes = Integer.parseInt(currentLine.split(":")[1]);
passwords.add(new Password(website, username, password, usedTimes));
website = "";
username = "";
password = "";
usedTimes = 0;
}
}
br.close();
Here is an example output: (I cant copy/paste the output so I place a picture)
So if anyone of you knows the answer, please tell me it would be great !
Thank you really much for reading this until here !
Julien.
It may be encoding issue. You have to check text file encoding, and then you have to try like this:
BufferedReader r = new BufferedReader(new InputStreamReader("ISO-XXXXX"))
I'm doing a million different regex replacements of a string. Thus I decided to save all String regex's and String replacements in a file.txt. I tried reading the file line by line and replacing it but it is not working.
replace_regex_file.txt
aaa zzz
^cc eee
ww$ sss
...
...
...
...
a million data
Coding
String user_input = "assume 100,000 words"; // input from user
String regex_file = "replace_regex_file.txt";
String result="";
String line;
try (BufferedReader reader = new BufferedReader(new FileReader(regex_file)) {
while ((line = reader.readLine()) != null) { // while line not equal null
String[] parts = line.split("\\s+", 2); //split process
if (parts.length >=2) {
String regex = parts[0]; // String regex stored in first array
String replace = parts[1]; // String replacement stored in second array
result = user_input.replaceAll(regex, replace); // replace processing
}
}
} System.out.println(result); // show the result
But it does not replace anything. How can I fix this?
Your current code will only apply the last matching regex, because you don't assign the result of the replacement back to the input string:
result = user_input.replaceAll(regex, replace);
Instead, try:
String result = user_input;
outside the loop and
result = result.replaceAll(regex, replace);
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"