I'm making a java program that would run on a local server.
Server takes request from client using PHP .
<?php
$file = fopen('temp.txt', 'a+');
$a=explode(':',$_GET['content']);
fwrite($file,$a[0].':'.$a[1]. '\n');
fclose($file);
?>
Now I have file "temp.txt" on local server.
Java Program should open the file read line by line and each like should be divided/exploded ":" (In a line there's only one ':' )
I have tried in many ways, but could not get exactly like how PHP splits the line.
Is it possible to use same/similar explode function in JAVA.
Yes, in Java you can use the String#split(String regex) method in order to split the value of a String object.
Update:
For example:
String arr = "name:password";
String[] split = arr.split(":");
System.out.println("Name = " + split[0]);
System.out.println("Password = " + split[1]);
You can use String.split in Java to "explode" each line with ":".
Edit
Example for a single line:
String line = "one:two:three";
String[] words = line.split(":");
for (String word: words) {
System.out.println(word);
}
Output:
one
two
three
Related
I have a long string which contains ~" & "~ etc.
but when I am trying to write it in xml the o/p is: ~"
please suggest a way to write the complete string including "(double quotes)
Below are my code:
for(String str:Parser.queryList){
Element query = doc.createElement("query");
view.appendChild(screen);
screen.appendChild(query);
query.setAttribute("query", str);
}
output: OP =~"=~"
I am trying to find the best way how to parse specific output from jsch when connecting and executing commands on a c7000 HP enclosure.
What I have done so far is written a program that connects to a hp enclosure, executes a command, retrieves the output of the command and converts it from a stream to a String.
I end up with this String
Server Blade #1 Information:
Type: Server Blade
Manufacturer: HP
Product Name: ProLiant BL280c G6
Part Number: 507865-B21
System Board Spare Part Number: 531337-001
Serial Number: XZ73616G9Z
UUID: 38926035-5636-5D43-3330-359274423959
Server Name: SERVERONE
Asset Tag: [Unknown]
ROM Version: I25 02/01/2013
CPU 1: Intel(R) Xeon(R) CPU E5520 # 2.27GHz (4 cores)
CPU 2: Intel(R) Xeon(R) CPU E5520 # 2.27GHz (4 cores)
Memory: 49152 MB
Now I need to extract some information from this string and put it in a variable/variables. I have tried with regex but don't seem to hack it. What I need is to end up with for example, product name "Proliant BL280c G6" in a string variable that I later can use, same goes with serial number or any other info in there. What I do not need is the preceding text as Type: or Part Number:. I only need to extract what comes after that.
I am pretty new with Java, learning lots every day, can anyone here point me in the right direction of the best way of solving this?
EDIT: Thank you very much all for quick responses. I got a few ideas now on how to solve the problem. The biggest help goes to showing me how to use regex expressions correctly. What i missed there was the possibility of excluding string pieces not needed ex. (?<=Product\sName:).
String delims = "\n"; //this is the identifier of a line change in java
String[] lines = result.split(delims);
for (int i=0;i<lines.length;i++)
{
System.out.println(lines[i]);
}
This code will save (and print) the lines in that String (assuming that what you posted is saved as a java String).
You have several ways to do this thou. Sure they will be more reasonable methods to make this (regex, parsers,...), but you can do this to check if a String contains a Substring:
str1.toLowerCase().contains(str2.toLowerCase())
So, for example, if you want to know if a line of lines[i] contains the word Product Name, just make this:
subS = "Product Name";
if (lines[x].toLowerCase().contains(subS.toLowerCase()));
//x being a number between 0 and the total of lines
As stated, this is a very rustical method, but it will work.
You can use Asier's method of splitting the lines by the newline character ('\n') and then to get the value of each one you can do line.substring(line.indexOf(":")+1, line.length()). You can also get the name of the parameter with line.substring(0, line.indexOf(":")).
You could make a HashMap and access them by key:
HashMap<String, String> map = new HashMap<String, String>(); //or new HashMap<>() if you are on Java 7
String str = "your server stuff goes here";
String[] lines = str.split("\n");
for(int i = 0; i < lines.length; i++)
{
String curline = lines[i];
int index = curline.indexOf(":");
map.put(curline.substring(0, index).trim(), curline.substring(index+1, curline.length()).trim());
}
Assuming, that your response is in source.txt, we read the file
File file = new File("source.txt");
BufferedReader fileReader = new BufferedReader(new FileReader(file));
Reading line by line we match it against regexp with lookup behind:
String line;
String LOOKUP_BEHIND = "(?<=[a-zA-Z0-9 ]:)";
while((line = fileReader.readLine())!= null){
Matcher matcher1 = Pattern.compile(LOOKUP_BEHIND + ".+").matcher(line);
if (matcher1.find()){
System.out.println(matcher1.group(0));
}
}
I want to call a PHP webservice from my J2ME program. Here is the PHP function called :
...
$req="SELECT DISTINCT a.adc_id FROM adc a INNER JOIN utilisateur u ON a.adc_id=u.adc_id INNER JOIN transfert t ON u.user_code = t.user_code
WHERE t.user_code ='". $user_code ."' AND t.date_transfert='".$datejour."'";
$query=mysql_query($req) ;
while($ligne = mysql_fetch_array($query))
{
$chaine .=$ligne['adc_id'].';';
$chaine .= "\r\n" ;
}
return $chaine;
As you see there is the "\r\n" new-line character returned by the webservice among the column data. For example the returned String is :
12011;Michael;12/12/2012;
13455;Sue;14/05/2011;
So how to "split" this String data in J2ME so that I will get an array String[] containing the values :
12011;Michael;12/12/2012; and 13455;Sue;14/05/2011; ?
You will either have to write your own tokenizer or use one of the many available on the net.
One example could be this one from nokia's page
Usage example:
Tokenizer t = new Tokenizer(yourString, "\r\n");
while (t.hasMoreTokens()) {
String token = t.nextToken();
//do something with token
}
I need to get a file name from file's absolute path (I am aware of the file.getName() method, but I cannot use it here).
EDIT: I cannot use file.getName() because I don't need the file name only; I need the part of the file's path as well (but again, not the entire absoulte path). I need the part of file's path AFTER certain path provided.
Let's say the file is located in the folder:
C:\Users\someUser
On windows machine, if I make a pattern string as follows:
String patternStr = "C:\\Users\\someUser\\(.*+)";
I get an exception: java.util.regex.PatternSyntaxException: Illegal/unsupported escape sequence for backslash.
If I use Pattern.quote(File.pathSeparator):
String patternStr = "C:" + Pattern.quote(File.separator) + "Users" + Pattern.quote(File.separator) + "someUser" + Pattern.quote(File.separator) + "(.*+)";
the resulting pattern string is: C:\Q;\EUsers\Q;\EsomeUser\Q;\E(.*+) which of course has no match with the actual fileName "C:\Users\someUser\myFile.txt".
What am I missing here? What is the proper way to parse file name?
What is the proper way to parse file name?
The proper way to parse a file name is to use File(String). Using a regex for this is going to hard-wire platform dependencies into your code. That's a bad idea.
I know you said you can't use File.getName() ... but that is the proper solution. If you would care to say why you can't use File.getName() perhaps I could suggest an alternative solution.
If you indeed want to use a regular expressions, you should use
String patternStr = "C:\\\\Users\\\\someUser\\\\(.*+)";
^^ ^^ ^^
instead.
Why? Your string literal
"C:\\Users\\someUser\\(.*+)"
is compiled to
C:\Users\someUser\(.*+)
Since \ is used for escaping in regular expressions too, you'll have to escape them "twice".
Regarding your edit:
You probably want to have a look at URI.relativize(). Example:
File base = new File("C:/Users/someUser");
File file = new File("C:/Users/someUser/someDir/someFile.txt");
String relativePath = base.toURI().relativize(file.toURI()).getPath();
System.out.println(relativePath); // prints "someDir/someFile.txt"
(Note that / works as file-separator on Windows machines too.)
Btw, I don't know what you have as File.separator on your system, but if it's set to \, then
"C:" + Pattern.quote(File.separator) + "Users" + Pattern.quote(File.separator) +
"someUser" + Pattern.quote(File.separator) + "(.*+)";
should yield
C:\Q\\EUsers\Q\\EsomeUser\Q\\E(.*+)
String patternStr = "C:\\Users\\someUser\\(.*+)";
Backslashes (\) are escape characters in the Java Language. Your string contains the following after compilation:
C:\Users\someUser\(.*+)
This string is then parsed as a regex, which uses backslashes as an escape character as well. The regex parser tries to understand the escaped \U, \s and \(. One of them is incorrect regarding the regex syntax (hence your exception), and none of them are what you are trying to achieve.
Try
String patternStr = "C:\\\\Users\\\\someUser\\\\(.*+)";
If you want to solve it by pattern you need to escape your Pattern properly
String patternStr = "C:\\\\Users\\\\someUser\\\\(.*+)";
Try putting double-double-backslashes in your pattern. You need a second backslash to escape one in the patter, plus you'll need to double each one to escape them in the string. Hence you'll end up with something like:
String patternStr = "C:\\\\Users\\\\someUser\\\\(.*+)";
Move from end of string to first occurrence of file path separator* or begin.
File paths separator can be / or \.
public static final char ALTERNATIVE_DIRECTORY_SEPARATOR_CHAR = '/';
public static final char DIRECTORY_SEPARATOR_CHAR = '\\';
public static final char VOLUME_SEPARATOR_CHAR = ':';
public static String getFileName(String path) {
if(path == null || path.isEmpty()) {
return path;
}
int length = path.length();
int index = length;
while(--index >= 0) {
char c = path.charAt(index);
if(c == ALTERNATIVE_DIRECTORY_SEPARATOR_CHAR || c == DIRECTORY_SEPARATOR_CHAR || c == VOLUME_SEPARATOR_CHAR) {
return path.substring(index + 1, length);
}
}
return path;
}
Try to keep it simple ;-).
Try this :
String ResultString = null;
try {
Pattern regex = Pattern.compile("([^\\\\/:*?\"<>|\r\n]+$)");
Matcher regexMatcher = regex.matcher(subjectString);
if (regexMatcher.find()) {
ResultString = regexMatcher.group(1);
}
} catch (PatternSyntaxException ex) {
// Syntax error in the regular expression
}
Output :
myFile.txt
Also for input : C:/Users/someUser/myFile.txt
Output : myFile.txt
What am I missing here? What is the proper way to parse file name?
The proper way to parse a file name is to use the APIs that are already provided for the purpose. You've stated that you can't use File.getName(), without explanation. You are almost certainly mistaken about that.
I cannot use file.getName() because I don't need the file name only; I need the part of the file's path as well (but again, not the entire absoulte path).
OK. So what you want is something like this.
// Canonicalize paths to deal with ".", "..", symlinks,
// relative files and case sensitivity issues.
String directory = new File(someDirectory).canonicalPath();
String test = new File(somePathname).canonicalPath();
if (!directory.endsWith(File.separator)) {
directory += File.separator;
}
if (test.startsWith(directory)) {
String pathInDirectory = test.substring(directory.length()):
...
}
Advantages:
No regexes needed.
Doesn't break if the path separator is something other than \.
Doesn't break if there are symbolic links on the path.
Doesn't break due to case sensitivity issues.
Suppose the file name has special characters, specially when supporting MAC where special characters are allowing in filenames, server side Path.GetFileName(fileName) fails and throws error because of illegal characters in path. The following code using regex come for the rescue.
The following regex take care of 2 things
In IE, when file is uploaded, the file path contains folders aswell (i.e. c:\samplefolder\subfolder\sample.xls). Expression below will replace all folders with empty string and retain the file name
When used in Mac, filename is the only thing supplied as its safari browser and allows special chars in file name
var regExpDir = #"(^[\w]:\\)([\w].+\w\\)";
var fileName = Regex.Replace(fileName, regExpDir, string.Empty);
I have a requirement in my project.
I generate a comment string in javascript.
Coping Option: Delete all codes and replace
Source Proj Num: R21AR058864-02
Source PI Last Name: SZALAI
Appl ID: 7924675; File Year: 7924675
I send this to server where I store it as a string in db and then after that I retrieve it back and show it in a textarea.
I generate it in javascript as :
codingHistoryComment += 'Source Proj Num: <%=mDefault.getFullProjectNumber()%>'+'\n';
codingHistoryComment += 'Source PI Last Name: <%=mDefault.getPILastName()%>'+'\n';
codingHistoryComment += 'Appl ID: <%=mDefault.getApplId()%>; File Year: <%=mDefault.getApplId()%>'+'\n';
In java I am trying to replace the \n to :
String str = soChild2.getChild("codingHistoryComment").getValue().trim();
if(str.contains("\\n")){
str = str.replaceAll("(\r\n|\n)", "<br>");
}
However the textarea still get populated with the "\n" characters:
Coping Option: Delete all codes and replace\nSource Proj Num: R21AR058864-02\nSource PI Last Name: SZALAI\nAppl ID: 7924675; File Year: 7924675\n
Thanks.
In java I am trying to replace the \n to
Don't replace the "\n". A JTextArea will parse that as a new line string.
Trying to convert it to a "br" tag won't help either since a JTextArea does not support html.
I always just use code like the following to populate a text area with text:
JTextArea textArea = new JTextArea(5, 20);
textArea.setText("1\n2\n3\n4\n5\n6\n7\n8\n9\n0");
// automatically wrap lines
jTextArea.setLineWrap( true );
// break lines on word, rather than character boundaries.
jTextArea.setWrapStyleWord( true );
From here.
Here is a test that works, try it out:
String str = "This is a test\r\n test.";
if(str.contains("\r\n")) {
System.out.println(str);
}
Assuming Javascript (since you try to replace with a HTML break line):
A HTML textarea newline should be a newline character \n and not the HTML break line <br>. Try to use the code below to remove extra slashes instead of your current if statement and replace. Don't forget to assign the value to the textarea after the replacement.
Try:
str = str.replaceAll("\\n", "\n");
I think your problem is here:
if(str.contains("\\n")){
Instead of "\\n" you just need "\n"
Then instead of "\n" you need "\\n" here:
str = str.replaceAll("(\r\n|\n)", "<br>");
By the way, the if(str.contains() is not really needed because it won't hurt to run replace all if there is no "\n" characters.