I have a path URL written in a file. I use the Scanner class to record that URL and output it to string variable "s". I then use the .equals() method to compare it and the path URL in my "gameDataFile" File object. The result is false, despite them being the same string as recorded in my console. What is happening here?
Path URL in file:
src\gameData\character_data.csv
Code snippet:
String s = in.next(); // in is a java.util.Scanner object
System.out.println(gameDataFile.getPath()); // gameDataFile is a java.io.File object
System.out.println(s);
System.out.println(s.equals(gameDataFile.getPath()));
Console output:
src\gameData\character_data.csv
src\gameData\character_data.csv
false
EDIT: as per request of #MTilsted, the following code snippet
String s = in.next();
System.out.println("'" + gameDataFile.getPath() + "'");
System.out.println("'" + s + "'");
System.out.println(s.equals(gameDataFile.getPath()));
Results in the console output:
'src\gameData\character_data.csv'
'
false
It seems to have replaced the URL with one single quotation mark
Try this instead:
String s = in.next(); // in is a java.util.Scanner object
System.out.println("'" + gameDataFile.getPath() + "'"); // gameDataFile is a java.io.File object
System.out.println("'" + s + "'");
System.out.println(s.equals(gameDataFile.getPath()));
Thanks to #VGR, the problem was that the String "s" contains an addition "Carriage return" character (ascii code 13).
The utf8 file in windows has a BOM (byte order mark) at the start of the file by default. It is invisible, but it really exist. I think it cause two string different even if they look the same.
add a backslash before the single quote
Related
I want to open a file using the argument I get via a socket. When I extract the filename using split(), the file does not open. But when I hardcode the value, it does open.
What am I missing here? I would expect the strings to be equal.
String name = str.split(";")[2];
System.out.println("Filename: " + name);
String path1 = new String("Input_Blatt3/Sample.txt");
String path2 = new String("Input_Blatt3/" + name);
System.out.println("Path1: " + path1);
System.out.println("Path2: " + path2);
System.out.println("path1.equals(path2) = " + path1.equals(path2));
Output:
Path1: Input_Blatt3/Sample.txt
Path2: Input_Blatt3/Sample.txt
path1.equals(path2) = false
There could be unprintable characters hidden in the String.
Use getBytes to get all the characters of a String and print those. You'll probably find something you didn't expect.
You need to iterate over the byte array to print each byte individually, as in the following method:
private static void printBytes(String string) {
System.out.println("printing " + string);
for (byte aByte : string.getBytes()) {
System.out.println( aByte );
}
}
Alternatively you could also replace everything that isn't a printable character with nothing.
There could be some trailing white spaces, which you would not see at the console output.
You can try name.strip() (or trim() if your JDK version is lower 11) to ensure that there's nothing but the file name in the string.
Also, you can find the index of the first mismatching character of these two strings using Arrays.mismatch():
int indexOfMismatch = Arrays.mismatch(str1.toCharArray(), str2.toCharArray());
In case if the strings are equal, indexOfMismatch would be -1.
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
I want to replace spaces from path string. I tried below but doesn't seems to be working :
String path = "/Users/TD/San Diego";
path=path.replaceAll(" ","\\ ");
System.out.println(path);
Goal is to convert
"/Users/TD/San Diego" to "/Users/TD/San\ Diego"
Any further space from string also needs to be replaced with "\ "
You could change
path = path.replaceAll(" ", "\\ ");
to escape the backslash
path = path.replaceAll(" ", "\\\\ ");
When I do that, I get (the requested)
/Users/TD/San\ Diego
Another option would be using String.replace like
path = path.replace(" ", "\\ ")
which outputs the same.
The suggested solution did not work for me (in Android Java).
So this is what I've came up with, after quite a few attempts:
path = path.replace(" ", (char) 92 + " ");
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/
When writing to a text file in java , how do I enter values into a new line
code snippet
while (rs.next()) {
int sport = rs.getInt("sport");
String name = rs.getString("name");
out.write(sport + " : " + name);}
the text file populates " value1 value2 value3...etc"
I want it to populate
value1
value2
value3
.
If 'out' is a PrintWriter, use println().
If 'out' is a BufferedWriter, use newLine().
If 'out' is some other Writer, use write('\n'), or append the newLine directly to the string you're writing. If you want the system's line separator, see System.getProperty() with the value "line.separator".
Very simple
out.write(sport + " : " + name + "\n");
That's all.
use out.write(10); to add new line. 10 is acsii character for newline. But it is not work for Indirect/Direct Buffer type FileChannel.