Hello this problem has been bugging me since a week I searched everywhere in vain. I have this code
................
while ((str = buff.readLine()) != null) {
String[] line = str.split(";");
String part1 = line[0];
String part2 = line[1];
String part3 = line[2];
String part4 = line[3];
String part5 = line[4];
if (c.equals(part3)) {
st = st + part1 + ";" + part2 + ";" + part3 + ";" + part4 + ";" + part5;
System.out.println(part1 + ";" + part2 + ";" + part3 + ";" + part4 + ";" + part5 + "\n");
fich1_tampon.write(st);
fich1_tampon.flush();
fich1_tampon.newLine();
++i;
}
}
System.out.println("F;" + i);
fich1_tampon.close();
buff.close();
}
the "System.out.println("F;" + i);" is ignored I don't know why. The code is very long but basically I'm looking for lines that have a certain String that was put in c and I'm writing those line in another file.
The result on my consoleis like this :
E;2014/02/19 20:21:06
File already exists.
N;2000;PU;Promotion iphone;232425
N;2001;PU;Promotion dell;232426
N;2002;PU;Promotion samsung;23242
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 2
at LireFichierDecouper.decouper(LireFichierDecouper.java:70)
at Main2.main(Main2.java:7)
Line 70 in LireFichierDecouper is "String part3 = line[2];"
PS:I'm very very new to java and eclipse, if you want me to post all the code to make it more clear I will.
If you work on eclipse, check "Problems" view for errors. Sometimes eclipse cannot compile code when your workspace has errors.
If you work on a running server, may be server do not recognize your changes. Restart it, may be this helps.
If double of above do not help you please explain exactly what you want and specify your development environment how it is.
A debugger would be helpful to see if you are reaching that code by adding a break point at the System.out.println. Also, where are you running the code? System.out.println would go where directed depending on how java is run. Please provide the command line if executing from the command line.
Related
I'm using Runtime.getRuntime.exec(String) to cut some songs with ffmpeg.
But when my song has a name with a blankspace it doesn't work ...
So before I cut the song, I want to replace every blank space of my songs by "\ ".
I did that :
String in = directory+songs.get(i);
String out = directory+"trimed_"+songs.get(i);
in.replaceAll(" "," \\ ");
out.replaceAll(" ", "\\ ");
String str = "ffmpeg -t 1 -i "+in+" -vcodec copy "+out;
Runtime.getRuntime().exec(str);
But it doesn't replace anything at all when I print str, am I missing something ?
Update : I tried every ideas given bellow and I didn't find a way to fix the problem. Hence, I replaced the blankspaces by "_" and it's working great.
Try
String in = directory+songs.get(i);
String out = directory+"trimed_"+songs.get(i);
/* in = in.replaceAll("\\s","\\\\ ");
out = out.replaceAll("\\s","\\\\ ");
*/
in = "\"" + in + "\"";
out = "\"" + out + "\"";
String str = "ffmpeg -t 1 -i " + in + " -vcodec copy " + out;
Runtime.getRuntime().exec(str);
System.out.println("Command executed " + str);
Note: I tested this code myself its working fine.
If it still not working then execute the command manually by copying the str from log and trace the error
It's so weird that the String + operation has a bug:
String path = "/app/" + monPHost.getUsername() + "/app/" + monProcessInfo.getRegion() + "/tf/bin";
System.out.println("here it ...." + path);
This is the result:
here it ..../app/aiams/app/791
Where has the "/tf/bin" gone?
Maybe monProcessInfo.getRegion() is ending with a carriage return. Try to pre-process it, strip it, and the concatenate with your string.
OR, try this:
String path = "/app/" + monPHost.getUsername() + "/app/" + monProcessInfo.getRegion();
path = path + "/tf/bin";
System.out.println("here it ...." + path);
As a quick work around for all the spaces you're getting:
String path = "/app/" + monPHost.getUsername() + "/app/" + monProcessInfo.getRegion().trim() + "/tf/bin";
System.out.println("here it ...." + path);
I recommend tracking this down in your process object and fixing it there, if you only ever expect an Integer result try to return one, failing fast & early can prevent a lot of downstream bugs.
Given in comment you mentioned monProcessInfo.getRegion() is giving you a String with lots of spaces, and you haven't mentioned the type of return for this method, here is what you may do:
If it is returning a String:
It will be as easy as
String path = "...." + monProcessInfo.getRegion().trim() + "/tf/bin";
If it is returning something else:
Given String concat in Java is relying on Object.toString(), you can change it to:
String path = "...." + monProcessInfo.getRegion().toString().trim() + "/tf/bin";
Since you mentioned that monProcessInfo.getRegion() returns lots of spaces, you can try trimming it before appending it to the later part of the string.
StringBuilder sb = new StringBuilder();
sb.append("/app/" + monPHost.getUsername() + "/app/");
String region = ("" + monProcessInfo.getRegion()).trim();
sb.append(region + "/tf/bin");
System.out.println("here it ...." + sb.toString());
I am trying to write to a text document with a specific format. Here's what I have right now.
String line = "";
double totalCost = 0;
Node curr = summary.head.next;
while(curr!=summary.tail)
{
line += [an assortment of strings and variables] +"\r";
totalCost += PRICELIST.get(curr.itemName)*curr.count;
curr = curr.next;
}
write.printf("%s" + "%n", line);
This is what the part adding onto line actually looks like.
"Item's name: " + curr.itemName + ", Cost per item: " + NumberFormat.getCurrencyInstance().format(PRICELIST.get(curr.itemName)) +
", Quantity: " + curr.count + ", Cost: " + NumberFormat.getCurrencyInstance().format(PRICELIST.get(curr.itemName)*curr.count) + "\r";
I've tried that with a newline character too. Before I had it working when the print statement was inside the loop meaning it only wrote one line at a time. I want to do it this way because I will have multiple threads writing to this file and this way any thread will not hold the lock for as long.
If using Java 7 or later you can use System.lineSeparator()
Use System.getProperty("line.separator") instead of "\r"
Cache ir for efficiency though.
First of all don't use
while(..){
result += newString
..
}
inside loop. This is very inefficient especially for long texts because each time you call
result += newString
you are creating new String which needs to copy content of result and append to it newStrint. So the more text you processed so far, the more it has to copy so it becomes slower.
Instead use
StringBuilder sb = new StringBuilder();
while(..){
sb.append(newString);
}
result = sb.toString.
which in your case should be something more like
sb.append("Item's name: ").append(curr.itemName)
.append(", Cost per item: ").append(NumberFormat.getCurrencyInstance().format(PRICELIST.get(curr.itemName)))
.append(", Quantity: ").append(curr.count )
.append(", Cost: ").append(NumberFormat.getCurrencyInstance().format(PRICELIST.get(curr.itemName) * curr.count))
.append(System.lineSeparator());
Also instead of
write.printf("%s" + "%n", line);
you should use simpler version, which is
write.println(line);
which automatically add line separator based on OS.
You can also try to use \n\r in combination. This helped in one of my projects.
I am making an application where I will be fetching tweets and storing them in a database. I will have a column for the complete text of the tweet and another where only the words of the tweet will remain (I need the words to calculate which words were most used later).
How I currently do it is by using 6 different .replaceAll() functions which some of them might be triggered twice. For example I will have a for loop to remove every "hashtag" using replaceAll().
The problem is that I will be editing as many as thousands of tweets that I fetch every few minutes and I think that the way I am doing it will not be too efficient.
What my requirements are in this order (also written in comments down bellow):
Delete all usernames mentioned
Delete all RT (retweets flags)
Delete all hashtags mentioned
Replace all break lines with spaces
Replace all double spaces with single spaces
Delete all special characters except spaces
Here is a Short and Compilable Example:
public class StringTest {
public static void main(String args[]) {
String text = "RT #AshStewart09: Vote for Lady Gaga for \"Best Fans\""
+ " at iHeart Awards\n"
+ "\n"
+ "RT!!\n"
+ "\n"
+ "My vote for #FanArmy goes to #LittleMonsters #iHeartAwards"
+ " htt…";
String[] hashtags = {"#FanArmy", "#LittleMonsters", "#iHeartAwards"};
System.out.println("Before: " + text + "\n");
// Delete all usernames mentioned (may run multiple times)
text = text.replaceAll("#AshStewart09", "");
System.out.println("First Phase: " + text + "\n");
// Delete all RT (retweets flags)
text = text.replaceAll("RT", "");
System.out.println("Second Phase: " + text + "\n");
// Delete all hashtags mentioned
for (String hashtag : hashtags) {
text = text.replaceAll(hashtag, "");
}
System.out.println("Third Phase: " + text + "\n");
// Replace all break lines with spaces
text = text.replaceAll("\n", " ");
System.out.println("Fourth Phase: " + text + "\n");
// Replace all double spaces with single spaces
text = text.replaceAll(" +", " ");
System.out.println("Fifth Phase: " + text + "\n");
// Delete all special characters except spaces
text = text.replaceAll("[^a-zA-Z0-9 ]+", "").trim();
System.out.println("Finaly: " + text);
}
}
Relying on replaceAll is probably the biggest performance killer as it compiles the regex again and again. The use of regexes for everything is probably the second most significant problem.
Assuming all usernames start with #, I'd replace
// Delete all usernames mentioned (may run multiple times)
text = text.replaceAll("#AshStewart09", "");
by a loop copying everything until it founds a #, then checking if the following chars match any of the listed usernames and possibly skipping them. For this lookup you could use a trie. A simpler method would be a replaceAll-like loop for the regex #\w+ together with a HashMap lookup.
// Delete all RT (retweets flags)
text = text.replaceAll("RT", "");
Here,
private static final Pattern RT_PATTERN = Pattern.compile("RT");
is a sure win. All the following parts could be handled similarly. Instead of
// Delete all special characters except spaces
text = text.replaceAll("[^a-zA-Z0-9 ]+", "").trim();
you could use Guava's CharMatcher. The method removeFrom does exactly what you did, but collapseFrom or trimAndCollapseFrom might be better.
According to the now closed question, it all boils down to
tweet = tweet.replaceAll("#\\w+|#\\w+|\\bRT\\b", "")
.replaceAll("\n", " ")
.replaceAll("[^\\p{L}\\p{N} ]+", " ")
.replaceAll(" +", " ")
.trim();
The second line seems to be redundant as the third one does remove \n too. Changing the first line's replacement to " " doesn't change the outcome an allows to aggregate the replacements.
tweet = tweet.replaceAll("#\\w*|#\\w*|\\bRT\\b|[^##\\p{L}\\p{N} ]+", " ")
.replaceAll(" +", " ")
.trim();
I've changed the usernames and hashtags part to eating also lone # or #, so that it doesn't need to be consumed by the special chars part. This is necessary for corrent processing of strings like !#AshStewart09.
For maximum performance, you surely need a precompiled pattern. I'd also re-suggest to use Guava's CharMatcher for the second part. Guava is huge (2 MB I guess), but you surely find more useful things there. So in the end you can get
private static final Pattern PATTERN =
Pattern.compile("#\\w*|#\\w*|\\bRT\\b|[^##\\p{L}\\p{N} ]+");
private static final CharMatcher CHAR_MATCHER = CharMacher.is(" ");
tweet = PATTERN.matcher(tweet).replaceAll(" ");
tweet = CHAR_MATCHER.trimAndCollapseFrom(tweet, " ");
You can inline all of the things that are being replaced with nothing into one call to replace all and everything that is replaced with a space into one call like so (also using a regex to find the hashtags and usernames as this seems easier):
text = text.replaceAll("#\w+|#\w+|RT", "");
text = text.replaceAll("\n| +", " ");
text = text.replaceAll("[^a-zA-Z0-9 ]+", "").trim();
Java newbie here, I'm having trouble setting a new line in this code:
String FnameTextboxText = FnameTextbox.getText();
String LastnameTextboxText = LastnameTextbox.getText();
String CourseTextboxText = CourseTextbox.getText();
Summary.setText("Firstname:" + " " + FnameTextboxText + "\nLastname:" + " " + LastnameTextboxText + "\nCourse:" + " " + CourseTextboxText);
Also tried something like: "\n" + "Lastname" But its no good.
Do you have any idea on how to make new lines. So that it'll look like this;
Firstname: x
Lastname: y
Course: Z
Using netbeans 6.8. On windows.
I guess you need to use TextArea.
First, use TextArea
Second, test using \r or \n or \r\n
Sometimes, people use \n to make new line and sometimes, like me, use \r\n to make new line