How to make string for file name? - java

I try to create file in storage and for file name I use webview.getTitle() string.
When I save file with name for example "Google.jpg" or "Foreca.jpg" it works well, but...
not all webpage titles is so clear.
For example:
"android - java.io.ioexception: open failed: einval (Invalid argument)
when saving a image to external storage - Stack Overflow:"
There is a lot of wrong characters, if I need this title put in file name.
Is there easy way to replace all this :;?!/<>- characters to ""?

Yes, you can use replaceAll():
String fileName = webview.getTitle();
filename = fileName.replaceAll("(\\p{Punct})","") // fixed \p
Check out the Java documentation for more.

Related

Creating a text file with java without using absolute path

following the question I asked before How to have my java project to use some files without using their absolute path? I found the solution but another problem popped up in creating text files that I want to write into.here's my code:
private String pathProvider() throws Exception {
//finding the location where the jar file has been located
String jarPath=URLDecoder.decode(getClass().getProtectionDomain().getCodeSource().getLocation().getPath(), "UTF-8");
//creating the full and final path
String completePath=jarPath.substring(0,jarPath.lastIndexOf("/"))+File.separator+"Records.txt";
return completePath;
}
public void writeRecord() {
try(Formatter writer=new Formatter(new FileWriter(new File(pathProvider()),true))) {
writer.format("%s %s %s %s %s %s %s %s %n", whichIsChecked(),nameInput.getText(),lastNameInput.getText()
,idInput.getText(),fieldOfStudyInput.getText(),date.getSelectedItem().toString()
,month.getSelectedItem().toString(),year.getSelectedItem().toString());
successful();
} catch (Exception e) {
failure();
}
}
this works and creates the text file wherever the jar file is running from but my problem is that when the information is been written to the file, the numbers,symbols, and English characters are remained but other characters which are in Persian are turned into question marks. like: ????? 111 ????? ????.although running the app in eclipse doesn't make this problem,running the jar does.
Note:I found the code ,inside pathProvider method, in some person's question.
Your pasted code and the linked question are complete red herrings - they have nothing whatsoever to do with the error you ran into. Also, that protection domain stuff is a hack and you've been told before not to write data files next to your jar files, it's not how OSes (are supposed to) work. Use user.home for this.
There is nothing in this method that explains the question marks - the string, as returned, has plenty of issues (see above), but NOT that it will result in question marks in the output.
Files are fundamentally bytes. Strings are fundamentally characters. Therefore, when you write code that writes a string to a file, some code somewhere is converting chars to bytes.
Make sure the place where that happens includes a charset encoding.
Use the new API (I think you've also been told to do this, by me, in an earlier question of yours) which defaults to UTF-8. Alternatively, specify UTF-8 when you write. Note that the usage of UTF-8 here is about the file name, not the contents of it (as in, if you put persian symbols in the file name, it's not about persian symbols in the contents of the file / in the contents you want to write).
Because you didn't paste the code, I can't give you specific details as there are hundreds of ways to do this, and I do not know which one you used.
To write to a file given a String representing its path:
Path p = Paths.get(completePath);
Files.write("Hello, World!", p);
is all you need. This will write as UTF_8, which can handle persian symbols (because the Files API defaults to UTF-8 if you specify no encoding, unlike e.g. new File, FileOutputStream, FileWriter, etc).
If you're using outdated APIs: new BufferedWriter(new OutputStreamWriter(new FileOutputStream(thePath), StandardCharsets.UTF-8) - but note that this is a resource leak bug unless you add the appropriate try-with-resources.
If you're using FileWriter: FileWriter is broken, never use this class. Use something else.
If you're converting the string on its own, it's str.getBytes(StandardCharsets.UTF_8), not str.getBytes().

How to get only the name of my PDF file

I'm developing a project for college which consist reading a CSV file and converting that to a PDF file. That part is fine, I have already done that.
In the end I need to show the name of the PDF file without the full path of where it was created. In other words, I just want the to show the name.
I search a lot to see if there is a simple method that show the name like Java has to show only the name of the File like
file.getName();
Whenever you use iText to create a PDF file, your code sets the target which usually is an OutputStream. If you use a FileOutputStream there, you know the file it writes to.
Thus, all you have to do to to show the name of the PDF File is to inspect your own code and check which target it sets.
Use getBaseName in Apache Commons IO.
getBaseName
public static String getBaseName(String filename)
Gets the base name, minus the full path and extension, from a full
filename.
This method will handle a file in either Unix or Windows format. The
text after the last forward or backslash and before the last dot is
returned.
a/b/c.txt --> c
a.txt --> a
a/b/c --> c
a/b/c/ --> ""
The output will be the same irrespective of the machine that the code
is running on.
Parameters:
filename - the filename to query, null returns null
Returns:
the name of the file without the path, or an empty string if none exists. Null bytes inside string will be removed
Source: https://commons.apache.org/proper/commons-io/javadocs/api-2.5/org/apache/commons/io/FilenameUtils.html#getBaseName(java.lang.String)
If you also need the extension, use getExtension. Which would probably always be .pdf, but you know, it's perfectly valid to have a PDF file without the .pdf filename extension. No sane person would do that but it is better to be prepared for insane users.

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);

Take off file path (home/user/file.txt = file.txt)?

So I've written a simple text editor in java, and it retrieves the file via showOpenDialog() and converts the filename into a string, so it can be displayed as the title:
String title = fc.getSelectedFile().toString();
But lets say I have the path "home/user/file.txt". How would I strip off the path and make it so the filename displays as "file.txt" only?
File getName() returns what you want i.e just the last name in the pathname's name sequence.
getSelectedFile() returns a File object; the easiest thing to do would be to just call getName() on the File object. If the path comes from someplace else, you could actually construct a File from it and then call getName().
String filename = title.substring(title.lastIndexOf("/"))
edit: brain's answer is better and more concise though :-)

Categories

Resources