Concatenating ArrayList of Strings into a single String using StringBuilder - java

In Java, I'm trying to concatenate the Strings from an ArrayList (called filesToReport) into a single String, as I want to display all file names in a single error message in a dialog box if they do not match certain criteria in a file opener. The solution I'm using now is a StringBuilder, and in principle it works. However, the problem is that if I eg. open three files that don't match the criteria, I first get one box listing file no. 1, then a box listing files no. 1 and 2, and then finally a box listing files no. 1, 2 and 3. The last box is the single box I want. Is there a way to achieve this?
My solution so far looks as follows:
if(filesToReport.size() > 0) {
StringBuilder sb = new StringBuilder();
for(String fileToReport : filesToReport) {
sb.append(fileToReport).append(",");
}
String incompatibleFiles = sb.toString();
String errorMessage = "The following files were not loaded \n" +
"as the are incompatible: \n" +
incompatibleFiles;
JOptionPane.showMessageDialog(frame, errorMessage);
}

I can't see the problem in this code snipplet, but my guess would be that you are appending the error message to the same filesToReport List. So it will contain the previous error messages.

As you were posting here, you may have corrected your error. The behavior you describe would have been caused by a misplaced brace:
if(filesToReport.size() > 0) {
StringBuilder sb = new StringBuilder();
for(String fileToReport : filesToReport) {
sb.append(fileToReport).append(",");
String incompatibleFiles = sb.toString();
String errorMessage = "The following files were not loaded \n" +
"as the are incompatible: \n" +
incompatibleFiles;
JOptionPane.showMessageDialog(frame, errorMessage);
}
}

Related

I want to highlight the text in some other color for a delta(difference) found when two strings are compared

extentreport1. I am writing a program to compare two strings using DiffUtils.diff(actualHTML, expHTML).
2. If there is a difference in two strings, it will print delta
3. I am reporting that delta in the extent report
4. I want to specifically highlight the change part in two strings in some other color while putting in extent report.
eg. String 1 :This is original text and String 2 :This is revised text
original and revised should be in some other color in extent report.
5. Can this be done?
public static void main(String[] args) throws DiffException {
String filePath=System.getProperty("user.dir") + "/test-
output/STMExtentReport" + new Date().getTime() + ".html";
ExtentReports extent = new ExtentReports();
ExtentHtmlReporter htmlReporter = new ExtentHtmlReporter(filePath);
extent.attachReporter(htmlReporter);
ExtentTest test = extent.createTest("TestName");
String originalText = "This is original text";
String revisedText = "This is revised text";
Patch<String> patch = DiffUtils.diff(originalText, revisedText);
if (patch.getDeltas().size() != 0) {
for (Delta<String> diffInActAndExpContent : patch.getDeltas())
{
System.out.println("delta:" + diffInActAndExpContent);
test.fail(diffInActAndExpContent.toString());
}
} else {
System.out.println("No content mismatch found by
ComputeDiffTwoFiles.");
}
extent.flush();
}
System.out.print("This is black! ");
System.err.println("This is red!");
But if you run this in cmd, both will be the same color.
As far as i understand, you are after character difference however DiffUtils provides line difference. you may have to write some logic to find out actual character difference between those 2 strings.
One way is to use StringUtils from apache lang package however it just gives the difference from first unmatched character between 2 strings. you can use below code if it solves your problem or otherwise write the logic to find out actual character difference and use it instead of StringUtils. Extent report is nothing but an html file and can be formatted in whatever way you like, see example to highlight in red color below-
Patch<String> patch = DiffUtils.diff(originalText, revisedText);
if (patch.getDeltas().size() != 0) {
for (Delta<String> diffInActAndExpContent : patch.getDeltas()) {
System.out.println("delta:" + diffInActAndExpContent);
String diff = StringUtils.difference(diffInActAndExpContent.getOriginal().toString(), diffInActAndExpContent.getRevised().toString());
test.fail(diffInActAndExpContent.toString().replace(diff, "<font color=red>" + diff + "</font>"));
}
} else {
System.out.println("No content mismatch found by ComputeDiffTwoFiles.");
}

Space in properties file [duplicate]

I am trying to load all the property names present in the properties file using the below code:
for(Enumeration<String> en = (Enumeration<String>) prop.propertyNames();en.hasMoreElements();){
String key = (String)en.nextElement();
System.out.println("Property name is "+key);
}
But my properties file has the below contents:
username=
password=
Parent file name=
Child file name =
After running the code I am getting output as :
username password Parent Child
If the property name has spaces, it is only returning the first word..
Can any one please tell me how to do this?
You can escape the spaces in your properties file, but I think it will start to look pretty ugly.
username=a
password=b
Parent\ file\ name=c
Child\ file\ name=d
You might be better of writing your own implementation with split() or indexOf() or whatever your heart desires to avoid any future bugs and/or headaches.
In Java.util.Properties , =, :, or white space character are key/value delimiter when load from property file.
Below are detailed Javadoc of its public void load(Reader reader)
The key contains all of the characters in the line starting with the first non-white space character and up to, but not including, the first unescaped =, :, or white space character other than a line terminator. All of these key termination characters may be included in the key by escaping them with a preceding backslash character. http://docs.oracle.com/javase/6/docs/api/
This is how I do it:
public class PropHelper {
final static String PROPERTY_FILEPATH = "blah/blah.properties";
static String getPropertyWithSpaces(String property, String delimiter) {
try {
FileReader reader = new FileReader(PROPERTY_FILEPATH);
Properties propertiesObj = new Properties();
propertiesObj.load(reader);
return propertiesObj.getProperty(property).replaceAll(delimiter, "");
} catch (Exception ex) {
System.out.println("FATAL ERROR: " + ex.getMessage());
System.exit(1);
}
return null;
}
}
Somewhere in .properties file:
settings = ` ⚙ Settings `
This is how I call it:
System.out.println("|" + PropHelper.getPropertyWithSpaces("settings", "`") + "|");
This method works with leading, internal and trailing spaces.
Enjoy!
It seems to be working fine for me; here is my code:
Properties prop = new Properties();
prop.setProperty("test1", "val1");
prop.setProperty("test number 2", "val number 2");
prop.setProperty("test 3", "val3");
prop.setProperty("test #4", "val #4");
for(Enumeration<String> en = (Enumeration<String>) prop.propertyNames();en.hasMoreElements();){
String key = (String)en.nextElement();
System.out.println("'" + key + "'='" + prop.getProperty(key) + "'");
}
And the output:
'test 3'='val3'
'test number 2'='val number 2'
'test1'='val1'
'test #4'='val #4'
You can compare that to yours as far as setting it goes, as our displaying seems to be the same. If you don't see anything, add your full code, and I'll take a look

Cleaning a file name in Java

I want to write a script that will clean my .mp3 files.
I was able to write a few line that change the name but I want to write an automatic script that will erase all the undesired characters $%_!?7 and etc. while changing the name in the next format Artist space dash Song.
File file = new File("C://Users//nikita//Desktop//$%#Artis8t_-_35&Son5g.mp3");
String Original = file.toString();
String New = "Code to change 'Original' to 'Artist - Song'";
File file2 = new File("C://Users//nikita//Desktop//" + New + ".mp3");
file.renameTo(file2);
I feel like I should make a list with all possible characters and then run the String through this list and erase all of the listed characters but I am not sure how to do it.
String test = "$%$#Arti56st_-_54^So65ng.mp3";
Edit 1:
When I try using the method remove, it still doesn't change the name.
String test = "$%$#Arti56st_-_54^So65ng.mp3";
System.out.println("Original: " + test);
test.replace( "[0-9]%#&\\$", "");
System.out.println("New: " + test);
The code above returns the following output
Original: $%$#Arti56st_-_54^So65ng.mp3
New: $%$#Arti56st_-_54^So65ng.mp3
I'd suggest something like this:
public static String santizeFilename(String original){
Pattern p = Pattern.compile("(.*)-(.*)\\.mp3");
Matcher m = p.matcher(original);
if (m.matches()){
String artist = m.group(1).replaceAll("[^a-zA-Z ]", "");
String song = m.group(2).replaceAll("[^a-zA-Z ]", "");
return String.format("%s - %s", artist, song);
}
else {
throw new IllegalArgumentException("Failed to match filename : "+original);
}
}
(Edit - changed whitelist regex to exclude digits and underscores)
Two points in particular - when sanitizing strings, it's a good idea to whitelist permitted characters, rather than blacklisting the ones you want to exclude, so you won't be surprised by edge cases later. (You may want a less restrictive whitelist than I've used here, but it's easy to vary)
It's also a good idea to handle the case that the filename doesn't match the expected pattern. If your code comes across something other than an MP3, how would you like it to respond? Here I've through an exception, so the calling code can catch and handle that appropriately.
String new = original.replace( "[0-9]%#&\\$", "")
this should replace almost all the characters you don't want
or you can come up with your own regex
https://docs.oracle.com/javase/tutorial/essential/regex/

Trim() in Java not working the way I expect? [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Query about the trim() method in Java
I am parsing a site's usernames and other information, and each one has a bunch of spaces after it (but spaces in between the words).
For example: "Bob the Builder " or "Sam the welder ". The numbers of spaces vary from name to name. I figured I'd just use .trim(), since I've used this before.
However, it's giving me trouble. My code looks like this:
for (int i = 0; i < splitSource3.size(); i++) {
splitSource3.set(i, splitSource3.get(i).trim());
}
The result is just the same; no spaces are removed at the end.
Thank you in advance for your excellent answers!
UPDATE:
The full code is a bit more complicated, since there are HTML tags that are parsed out first. It goes exactly like this:
for (String s : splitSource2) {
if (s.length() > "<td class=\"dddefault\">".length() && s.substring(0, "<td class=\"dddefault\">".length()).equals("<td class=\"dddefault\">")) {
splitSource3.add(s.substring("<td class=\"dddefault\">".length()));
}
}
System.out.println("\n");
for (int i = 0; i < splitSource3.size(); i++) {
splitSource3.set(i, splitSource3.get(i).substring(0, splitSource3.get(i).length() - 5));
splitSource3.set(i, splitSource3.get(i).trim());
System.out.println(i + ": " + splitSource3.get(i));
}
}
UPDATE:
Calm down. I never said the fault lay with Java, and I never said it was a bug or broken or anything. I simply said I was having trouble with it and posted my code for you to collaborate on and help solve my issue. Note the phrase "my issue" and not "java's issue". I have actually had the code printing out
System.out.println(i + ": " + splitSource3.get(i) + "*");
in a for each loop afterward.
This is how I knew I had a problem.
By the way, the problem has still not been fixed.
UPDATE:
Sample output (minus single quotes):
'0: Olin D. Kirkland                                          '
'1: Sophomore                                          '
'2: Someplace, Virginia  12345<br />VA SomeCity<br />'
'3: Undergraduate                                          '
EDIT the OP rephrased his question at Query about the trim() method in Java, where the issue was found to be Unicode whitespace characters which are not matched by String.trim().
It just occurred to me that I used to have this sort of issue when I worked on a screen-scraping project. The key is that sometimes the downloaded HTML sources contain non-printable characters which are non-whitespace characters too. These are very difficult to copy-paste to a browser. I assume that this could happened to you.
If my assumption is correct then you've got two choices:
Use a binary reader and figure out what those characters are - and delete them with String.replace(); E.g.:
private static void cutCharacters(String fromHtml) {
String result = fromHtml;
char[] problematicCharacters = {'\000', '\001', '\003'}; //this could be a private static final constant too
for (char ch : problematicCharacters) {
result = result.replace(ch, ""); //I know, it's dirty to modify an input parameter. But it will do as an example
}
return result;
}
If you find some sort of reoccurring pattern in the HTML to be parsed then you can use regexes and substrings to cut the unwanted parts. E.g.:
private String getImportantParts(String fromHtml) {
Pattern p = Pattern.compile("(\\w*\\s*)"); //this could be a private static final constant as well.
Matcher m = p.matcher(fromHtml);
StringBuilder buff = new StringBuilder();
while (m.find()) {
buff.append(m.group(1));
}
return buff.toString().trim();
}
Works without a problem for me.
Here your code a bit refactored and (maybe) better readable:
final String openingTag = "<td class=\"dddefault\">";
final String closingTag = "</td>";
List<String> splitSource2 = new ArrayList<String>();
splitSource2.add(openingTag + "Bob the Builder " + closingTag);
splitSource2.add(openingTag + "Sam the welder " + closingTag);
for (String string : splitSource2) {
System.out.println("|" + string + "|");
}
List<String> splitSource3 = new ArrayList<String>();
for (String s : splitSource2) {
if (s.length() > openingTag.length() && s.startsWith(openingTag)) {
String nameWithoutOpeningTag = s.substring(openingTag.length());
splitSource3.add(nameWithoutOpeningTag);
}
}
System.out.println("\n");
for (int i = 0; i < splitSource3.size(); i++) {
String name = splitSource3.get(i);
int closingTagBegin = splitSource3.get(i).length() - closingTag.length();
String nameWithoutClosingTag = name.substring(0, closingTagBegin);
String nameTrimmed = nameWithoutClosingTag.trim();
splitSource3.set(i, nameTrimmed);
System.out.println("|" + splitSource3.get(i) + "|");
}
I know that's not a real answer, but i cannot post comments and this code as a comment wouldn't fit, so I made it an answer, so that Olin Kirkland can check his code.

java reading numbers, interpreting as octal, want interpreted as string

i am having an issue, where java is reading an array list from a YAML file of numbers, or strings, and it is interpreting the numbers as octal if it has a leading 0, and no 8-9 digit.
is there a way to force java to read the yaml field as a string?
code:
ArrayList recordrarray = (ArrayList) sect.get("recordnum");
if (recordrarray != null) {
recno = join (recordrarray, " ");
}
HAVE ALSO TRIED:
Iterator<String> iter = recordrarray.iterator();
if (iter.hasNext()) recno = " " +String.valueOf(iter.next());
System.out.println(" this recnum:" + recno);
while (iter.hasNext()){
recno += ""+String.valueOf(iter.next()));
System.out.println(" done recnum:" + String.valueOf(iter.next()));
}
the input is such:
061456 changes to 25390
061506 changes to 25414
061559 -> FINE
it took a while to figure out what it was doing, and apparently this is a common issue for java,
ideas?
thanks
edit: using jvyaml
yaml:
22:
country_code: ' '
description: ''
insection: 1
recordnum:
- 061264
type: misc
yaml loading:
import org.jvyaml.YAML;
Map structure = new HashMap();
structure = (Map) YAML.load(new FileReader(structurefn)); // load the structure file
Where are you reading the file? The problem lies in where the file contents are being read. Most likeley the recordarray list contains integers, ie. they have alreadey been parsed. Find the place where the records are being read. Maybe you are doing something like this:
int val = Integer.parseInt(record);
Use this instead:
int val = Integer.parseInt(record, 10);

Categories

Resources