I have a function that accepts a message in String form. The message looks like this : "HTTP/1.1 GET /1/ \n"
I have been using the java.String.split method to break down the string into three smaller substrings, version, command, and number. Then I reconstruct the oringal string from the substrings and output it.
However, when I run teh function the program results in ArrayIndex out of bounds : 1, but still functions properly. But when I run the program step by step in the debugger (netbeans) the program does not result in the ArrayIndex out of bounds nonesense and functions as normal
Any suggestions?
Sam
String output = "";
String[] tokens = clientMessage.split(" ");
String version = tokens[0];
String command = tokens[1];
String potNum = tokens[2];
output = version + " " + command + " " + potNum;
EDIT yes, the program is multithreaded, the clientMsessage string contains "HTTP/1.1 GET /1/ \n" all the time, the value fo clientMessage never changes. The clientMessage is a string sent from a client program and then processed on the server and the output is snet back tot eh client but I keep getting the array errors
I suggest you print out/log your inputs. I suspect you are doing something differently when you debug your program. Its possible this works the first time you call it but when its called again, it fails.
Add before the split.
System.out.println("clientMessage >" + clientMessage +"<");
If your output looks like
clientMessage >HTCPCP/1.0 PROPFIND /1/<
clientMessage >HTCPCP/1.0 PROPFIND /1/<
clientMessage ><
It appears you have an empty request message. I imagine this means the client will not be sending more requests and you have to handle this differently.
ArrayIndexOutOfBounds arises when you are accessing index of an array which does not have any values means in your case tokens[1] does not exists. When debugging are you using same string as input??
Sorry this is not an answer but just an additional question to find what is actually wrong and comments are too small to put that much code. The following works for me, so one of your asumptions is wrong:
import java.io.IOException;
public class Main {
public static void main(String[] args) throws IOException {
String clientMessage = "HTTP/1.1 GET /1/ \n";
String[] tokens = clientMessage.split(" ");
String version = tokens[0];
String command = tokens[1];
String potNum = tokens[2];
System.err.println(version + " " + command + " " + potNum);
}
}
It runs OK on my side. I would have to guess that sometimes clientMessage is a value that does not contain enough spaces to be seperated in 3 parts.
Perhaps there is more to the code than you are including here. I put your code in a class as follows and it compiles and runs without error. Is there something missing?
public class Andrew {
public static void main(String args[]) {
String output = "";
String clientMessage = "HTTP/1.1 GET /1/ \n";
String[] tokens = clientMessage.split(" ");
String version = tokens[0];
String command = tokens[1];
String potNum = tokens[2];
output = version + " " + command + " " + potNum;
System.out.println(output);
}
}
Related
im trying to do string .contains() for specific lines on text
im reading in lines of a file using Files.readAlllines.
im trying to do
Path c1=Paths.get(prop.getProperty("testPWP"));
List<String> newLines1 = new ArrayList<String>();
for (String line : Files.readAllLines(c1, StandardCharsets.UTF_8)) {
if (line.contains("return test ;\r\n" + " }")) {
newLines1.add( line.replace("return test ;\r\n" +
" }", "return test ;\r\n" +
" }*/"));
}
else {
newLines1.add(line);
}
}
Files.write(c1, newLines1, StandardCharsets.UTF_8);
im basically trying to comment the } after the return statement but the contains function not recongnizing it as its in new line in the file.
Any help on this issue?
As you may have noticed, Files.readAllLines reads all lines and returns a list in which each string represents a line. To accomplish what you are trying to do, you either need to read the entire file into a single string, or concatenate the strings you already have, or change your approach of substitution. The easiest way would be to read the entire contents of the file into one string, which can be accomplished as follows:
String content = new String(Files.readAllBytes(Paths.get("path to file")));
or if you are using Java 11 or higher:
String content = Files.readString(Paths.get("path to file"));
You can use the replaceable parameter to replace the regex.
Demo:
public class Main {
public static void main(String[] args) {
String find = "return test ;\r\n" + " }";
String str = "Hello return test ;\r\n" + " } Hi Bye";
boolean found = str.contains(find);
System.out.println(found);
if (found) {
str = str.replaceAll("(" + find + ")", "/*$1*/");
}
System.out.println(str);
}
}
Output:
true
Hello /*return test ;
}*/ Hi Bye
Here $1 specifies the capturing group, group(1).
In your program, the value of str can be populated as follows:
String str = Files.readString(path, StandardCharsets.US_ASCII);
In case your Java version is less than 11, you do it as follows:
String str = new String(Files.readAllBytes(Paths.get(path)), StandardCharsets.US_ASCII);
I am working in Java. I have list of parameters stored in a string which is coming form excel. I want to split it only at starting hyphen of every new line. This string is stored in every excel cell and I am trying to extract it using Apache poi. The format is as below:
String text =
"- I am string one\n" +
"-I am string two\n" +
"- I am string-three\n" +
"with new line\n" +
"-I am string-four\n" +
"- I am string five";
What I want
array or arraylist which looks like this
[I am string one,
I am string two,
I am string-three with new line,
I am string-four,
I am string five]
What I Tried
I tried to use split function like this:
String[] newline_split = text.split("-");
but the output I get is not what I want
My O/P
[, I am string one,
I am string two,
I am string, // wrong
three // wrong
with new line, // wrong
I am string, // wrong!
four, // wrong!
I am string five]
I might have to tweak split function a bit but not able to understand how, because there are so many hyphens and new lines in the string.
P.S.
If i try splitting only at new line then the line - I am string-three \n with new line breaks into two parts which again is not correct.
EDIT:
Please know that this data inside string is incorrectly formatted just like what is shown above. It is coming from an excel file which I have received. I am trying to use apache poi to extract all the content out of each excel cell in a form of a string.
I intentionally tried to keep the format like what client gave me. For those who are confused about description inside A, I have changed it because I cannot post the contents on here as it is against privacy of my workplace.
You can
remove line separators (replace it with space) if they don't have - after it (in next line): .replaceAll("\\R(?!-)", " ") should do the trick
\R (written as "\\R" in string literal) since Java 8 can be used to represent line separators
(?!...) is negative-look-ahead mechanism - ensures that there is no - after place in which it was used (will not include it in match so we will not remove potential - which ware matched by it)
then remove - placed at start of each line (lets also include followed whitespaces to trim start of the string). In other words replace - placed
after line separators: can be represented by "\\R"
after start of string: can be represented by ^
This should do the trick: .replaceAll("(?<=\\R|^)-\\s*","")
split on remaining line separtors: .split("\\R")
Demo:
String text =
"- I am string one\n" +
"-I am string two\n" +
"- I am string-three\n" +
"with new line\n" +
"-I am string-four\n" +
"- I am string five";
String[] split = text.replaceAll("\\R(?!-)", " ")
.replaceAll("(?<=\\R|^)-\\s*","")
.split("\\R");
for (String s: split){
System.out.println("'"+s+"'");
}
Output (surrounded with ' to show start and end of results):
'I am string one'
'I am string two'
'I am string-three with new line'
'I am string-four'
'I am string five'
This is how I would do:
import java.util.*;
public class MyClass {
public static void main(String args[]) {
String A = "- I am string one \n" +
" -I am string two\n" +
" - I am string-three \n" +
" with new line\n" +
" -I am string-four\n" +
"- I am string five";
String[] s2 = A.split("\r?\n");
List<String> lines = new ArrayList<String>();
String line = "";
for (int i = 0; i < s2.length; i++) {
String ss = s2[i].trim();
if (i == 0) { // first line MUST start with "-"
line = ss.substring(1).trim();
} else if (ss.startsWith("-")) {
lines.add(line);
ss = ss.substring(1).trim();
line = ss;
} else {
line = line + " " + ss;
}
}
lines.add(line);
System.out.println(lines.toString());
}
}
I hope it helps.
A little explanation:
I will process line by line, trimming each one.
If it starts with '-' it means the end of the previous line, so I include it in the list. If not, I concatenate with the previous line.
looks as if you are splitting the FIRST - of each line, so you need to remove every instance of a "newline -"
str.replace("\n-", '\n')
then Remove the initial "-"
str = str.substring(1);
I have a logging function in CSharp and Java that I use in walking the stack. How do I make each log print to a new line only. Below are my Java and CSharp Functions.
public static void LogFunctionCall(String parameters){
Object trace = Thread.currentThread().getStackTrace()[3];
android.util.Log.i("##################" + trace.toString()+ "", parameters );
}
the java version is this
public static void LogFunctionCall(string parameters,
[System.Runtime.CompilerServices.CallerMemberName] string methodName = "",
[System.Runtime.CompilerServices.CallerFilePath] string sourceFilePath = "",
[System.Runtime.CompilerServices.CallerLineNumber] int sourceLineNumber = 0)
{
var stackFrame = new StackFrame(1);
var callerMethod = stackFrame.GetMethod();
var className = callerMethod.DeclaringType;
System.Diagnostics.Trace.WriteLine("CCCCCCCCCCCCCCCC" + " " + className + " " + methodName + " " + sourceLineNumber + " " + parameters + "\n");
}
I code on a windows machine.
Please where exactly do I need to place the new line character. I tried this
public static void LogFunctionCall(String parameters){
Object trace = Thread.currentThread().getStackTrace()[3];
android.util.Log.i("##################" + trace.toString()+ "", parameters + "\n" );
}
but I still saw some of the logs being clumped up on a single line.
Instead of \n, try \r\n (carriage return and newline). Some text editors will display differently, so the newline may be in there, but whatever app you're using to read the logs might not be displaying it correctly.
You could also try
System.lineSeparator();
I've seen instances where the /n won't work but the lineSep does.
Also, because it hasn't been mentioned, Environment.NewLine will give you the new line character that is configured for the current environment.
I have a string from which I need to remove all mentioned punctuations and spaces. My code looks as follows:
String s = "s[film] fever(normal) curse;";
String[] spart = s.split("[,/?:;\\[\\]\"{}()\\-_+*=|<>!`~##$%^&\\s+]");
System.out.println("spart[0]: " + spart[0]);
System.out.println("spart[1]: " + spart[1]);
System.out.println("spart[2]: " + spart[2]);
System.out.println("spart[3]: " + spart[3]);
System.out.println("spart[4]: " + spart[4]);
But, I am getting some elements which are blank. The output is:
spart[0]: s
spart[1]: film
spart[2]:
spart[3]: fever
spart[4]: normal
My desired output is:
spart[0]: s
spart[1]: film
spart[2]: fever
spart[3]: normal
spart[4]: curse
Try with this:
public static void main(String[] args) {
String s = "s[film] fever(normal) curse;";
String[] spart = s.split("[,/?:;\\[\\]\"{}()\\-_+*=|<>!`~##$%^&\\s]+");
for (String string : spart) {
System.out.println("'"+string+"'");
}
}
output:
's'
'film'
'fever'
'normal'
'curse'
I believe it is because you have a Greedy quantifier for space at the end there. I think you would have to use an escape sequence for the plus sign too.
String spart = s.replaceAll( "\\W", " " ).split(" +");
I have written some code and used a string that I concatentated using the += (as I only do it a couple of times.
Later on I used another string and used the concat() function. and the concatenation didn't work.
So I wrote a little method in Junit (with eclipse)...
#Test
public void StingConcatTest(){
String str = "";
str += "hello ";
str += " and goodbye";
String conc="";
conc.concat("hello ");
conc.concat(" and goodbye");
System.out.println("str is: " + str + "\nconc is: "+ conc);
The output is...
str is: hello and goodbye
conc is:
So either I'm going mad, I'm doing something wrong (most likely), there is an issue in JUNIT, or there is a problem with my JRE / eclipse or something.
Note that stringbuilders are working fine.
David.
Ok, we see this question at least couple of times a day.
Strings are immutable, so all operations on String results in new String.
conc= conc.concat("hello "); you need to reassign result to string again
You have to try with:
String conc="";
conc = conc.concat("hello ");
conc = conc.concat(" and goodbye");
System.out.println("str is: " + str + "\nconc is: "+ conc);
For sake of optimization you can write:
String conc="";
conc = conc.concat("hello ").concat(" and goodbye");
System.out.println("str is: " + str + "\nconc is: "+ conc);
If you plan on concatenating multiple Strings you could also use StringBuilder:
StringBuilder builder = new StringBuilder();
builder.append("hello");
builder.append(" blabla");
builder.append(" and goodbye");
System.out.println(builder.toString());
concat returns a String. It doesn't update the original String.
concat() returns the concatenated string.
public static void main(String [] args) {
String s = "foo";
String x = s.concat("bar");
System.out.println(x);
}
String.concat doesn't change the string it is called on - it returns a new string which is the string and the argument concatenated together.
By the way: string concatenation using concat or += is not very performant. You should use the class StringBuilder instead.