Reading path from ini file, backslash escape character disappearing? - java

I'm reading in an absolute pathname from an ini file and storing the pathname as a String value in my program. However, when I do this, the value that gets stored somehow seems to be losing the backslash so that the path just comes out one big jumbled mess? For example, the ini file would have key, value of:
key=C:\folder\folder2\filename.extension
and the value that gets stored is coming out as C:folderfolder2filename.extension.
Would anyone know how to escape the keys before it gets read in?
Let's also assume that changing the values of the ini file is not an alternative because it's not a file that I create.

Try setting the escape property to false in Ini4j.
http://ini4j.sourceforge.net/apidocs/org/ini4j/Config.html#setEscape%28boolean%29
You can try:
Config.getGlobal().setEscape(false);

If you read the file and then translate the \ to a / before processing, that would work. So the library you are using has a method Ini#load(InputStream) that takes the INI file contents, call it like this:
byte[] data = Files.readAllBytes(Paths.get("directory", "file.ini");
String contents = new String(data).replaceAll("\\\\", "/");
InputStream stream = new ByteArrayInputStream(contents.getBytes());
ini.load(stream);
The processor must be doing the interpretation of the back-slashes, so this will give it data with forward-slashes instead. Or, you could escape the back-slashes before processing, like this:
String contents = new String(data).replaceAll("\\\\", "\\\\\\\\");

Related

How to get File Path with double-backslashes in Java

I have a program where I save school grades in a .txt File.
I want to let the user choose where this File should be saved.
It works with the JFileChooser find but Java have a problem with the
FilePath.
The filepath from the JFileChooser looks like this:
C:\Users...\Documents\n.txt
But if I want to read the TextFile in the Program Java says that
it couldn't find the Filepath.
It should look like this:
C:\Users\...\Documents\n.txt
How can I get the Path with double-backslashes?
public void actionPerformed(ActionEvent e) {
JFileChooser jf = new JFileChooser();
jf.showSaveDialog(null);
String fPath = jf.getSelectedFile().getPath();
fPath.replaceAll('\', '\\');
System.out.println(p);
}
that does not work it says invalid character constant
There are some places where the backslash serves as escape character, and must be escaped, to be simply the backslash of a Windows path separator.
These places are inside .properties files, java String literals and some more.
You could for Windows paths alternatively use a slash (POSIX compliance of Windows).
fPath = fPath.replace('\\', '/');
Backslash:
fPath = fPath.replace("\\", "\\\\");
The explanation is that a single backslash inside char and string literals must be escaped: two backslashes represent a single backslash.
With regular expressions (replaceAll) a backlash is used as command: a digit is expressed as \d and as java String: "\\d". Hence the backslash itself becomes (behold):
fPath = fPath.replaceAll("\\\\", "\\\\\\\\"); // PLEASE NOT
I almost did not see it, but methods on String do not alter it, but return a new value, so one needs to assign the result.
When using hard coded file names in Java you should always use forward slashes / as file separators. Java knows how to handle them on Windows.
Also you should not use absolute paths. You don't know if that paths will exist at the target system. You should use either relative paths starting with your classpath as root "/..." or get some system dependen places from System.getProperty() https://docs.oracle.com/javase/8/docs/api/java/lang/System.html#getProperties--
Multiple issues in your code:
public void actionPerformed(ActionEvent e) {
JFileChooser jf = new JFileChooser();
jf.showSaveDialog(null);
String fPath = jf.getSelectedFile().getPath();
// fPath is a proper file path. This can be used directly with
// new File(fPath). The contents will contain single \ character
// as Path separator
fPath.replaceAll('\', '\\');
// I guess you are trying to replace a single \ character with \\
// character. You need to escape the \ character. You need to
// consider that both parameters are regexes.
// doing it is:
// fPath.replaceAll("\\\\", "\\\\\\\\");
// And then you need to capture the return value. Strings are
// immutable in java. So it is:
// fPath = fPath.replaceAll("\\\\", "\\\\\\\\");
System.out.println(p);
// I don't know what p is. I guess you want to use fPath
}
That said, I do not understand why you want to convert the path returned by JFileChooser.
You don't need the file path with double backslashes in Java. Double backslashes are for:
The Java compiler, inside string literals.
The Java regex compiler.
Everywhere else you can obtain backslashes, or use forward slashes.
Possibly you are looking for java.util.Properties?

How to validate a file name in java

I am working with a coverity issue which i need to validate a file name
using regEx in java . In my application support .pdf , .txt , csv etc . My
file name getting as xxx.txt from user . i want to validate my file name
with proper extension format and not included any special character other
than dot ( eg .txt) .
filePath = properties.getProperty("DOCUMENT.LIBRARY.LOCATION");
String fileName = (String) request.getParameter("read");
Only If the file path is completed itsproper validation, the below code should be work .
filePath += "/" + fileName;
This is a terrible answer as it only verifies the filename ends with the desired extension, but doesn't verify the rest of the filename as requested in the original question. Something more like this would be MUCH better:
fileName.matches("[-_. A-Za-z0-9]+\\.(pdf|txt|csv)");
This ensures the filename contains only ONE OR MORE -, _, PERIOD, SPACE, or alphanumeric characters, followed by exactly one of .pdf, .txt or .csv at the end of the filename. Your system might allow other characters in filenames and you could add them to this list if desired. An alternate, less secure approach is to prevent 'bad' characters something like:
fileName.matches("[^/\]+\\.(pdf|txt|csv)");
Which simply prevents / or \ characters from being in the file name before the required ending extension. But this doesn't prevent potentially other dangerous characters, like NULL bytes, for example.
Have a look at String.endsWith() method
if (fileName.endsWith(".pdf")) {
// do something
}
Or use the method String.matches()
fileName.matches("\\.(pdf|txt|csv)$")

Java saving a file with special characters in file name

I'm having a problem on Java file encoding.
I have a Java program will save a input stream as a file with a given file name, the code snippet is like:
File out = new File(strFileName);
Files.copy(inStream, out.toPath());
It works fine on Windows unless the file name contains some special characters like Ö, with these characters in the file name, the saved file will display a garbled file name on Windows.
I understand that by applying JVM option -Dfile.encoding=UTF-8 this issue can be fixed, but I would have a solution in my code rather than ask all my users to change their JVM options.
While debugging the program I can see the file name string always shows the correct character, so I guess the problem is not about internal encoding.
Could someone please explain what went wrong behind the scene? and is there a way to avoid this problem programmatically? I tried get the bytes from the string and change the encoding but it doesn't work.
Thanks.
Using the URLEncoder class would work:
String name = URLEncoder.encode("fileName#", "UTF-8");
File output = new File(name);

File Compression in Java (Hadoop DefaultCodec) - how to make it human readable?

I have a file was compressed with org.apache.hadoop.io.compress.DefaultCodec I'd like to revert this file back to its original format - which is a string in JSON format.
I'm not too sure about how to use DefaultCodec's documentation to make this happen. Can someone give me an example of how this would look like? Here's what I have so far, I have no idea if I'm on the right track...
//grab my file (it's on S3)
S3Object fileOnS3 = s3Service.getObject("mys3bucket", "myfilename");
DefaultCodec codec = new DefaultCodec();
Decompressor decompressor = codec.createDecompressor();
//does the following line create a input stream that parses DefaultCodec into uncompressed form?
CompressionInputStream is = codec.createInputStream(fileOnS3.getDataInputStream(), decompressor);
//also, I have no idea what to do from here.
I'd like to store the uncompressed version in a String variable, since I know the file is a small one-liner.
I would try the following:
Decompress the file using the hdfs shell command -text and unix shell, like that:
hadoop dfs -text /path/on/hdfs/ > /local/path/for/local/raw/file
Load the file using SequenceFileInputFormat for the input and set as output TextOutputFormat, using an identity mapper (and zero reducers).
I would go for the first option, especially if you say that the input file is a small string. If you want to load this file in a String variable, you can either load the file (which seems unnecessarily expensive), or store the output of -text command immediately in a String (skipping the part after >).

Appending to JTextArea is not creating a line break on '\n'

I'm loading string resources from a text file (so as to not have to rebuild if I need to change them) which when appended to the JTextArea displays as "Some sentence,\n on the same line."
When I hard code the exact same String, it appends fine.
Where could this be going wrong?
What does your text file look like? If "\n" is in the text file it's probably copied literally, i.e. it's not treated as an escape sequence.
EDIT: You could try reading the text file as a property file and automatically have e.g. \n parsed a newline.
Properties p = new Properties();
InputStream fileStream = new FileInputStream("myfile.txt");
p.load(fileStream);
String value = p.getProperty(key);
In the text file do this...
"1st_Half_of_String"+"\n"+"2nd_Half_of_String"

Categories

Resources