Remove filename from a URL/Path in java - java

How do I remove the file name from a URL or String?
String os = System.getProperty("os.name").toLowerCase();
String nativeDir = Game.class.getProtectionDomain().getCodeSource().getLocation().getFile().toString();
//Remove the <name>.jar from the string
if(nativeDir.endsWith(".jar"))
nativeDir = nativeDir.substring(0, nativeDir.lastIndexOf("/"));
//Load the right native files
for(File f : (new File(nativeDir + File.separator + "lib" + File.separator + "native")).listFiles()){
if(f.isDirectory() && os.contains(f.getName().toLowerCase())){
System.setProperty("org.lwjgl.librarypath", f.getAbsolutePath()); break;
}
}
That's what I have right now, and it work. From what I know, because I use "/" it will only work for windows. I want to make it platform independent

Consider using org.apache.commons.io.FilenameUtils
You can extract the base path, file name, extensions etc with any flavor of file separator:
String url = "C:\\windows\\system32\\cmd.exe";
String baseUrl = FilenameUtils.getPath(url);
String myFile = FilenameUtils.getBaseName(url)
+ "." + FilenameUtils.getExtension(url);
System.out.println(baseUrl);
System.out.println(myFile);
Gives,
windows\system32\
cmd.exe
With url; String url = "C:/windows/system32/cmd.exe";
It would give;
windows/system32/
cmd.exe

By utilizing java.nio.file; (afaik introduced after J2SE 1.7) this simply solved my problem:
Path path = Paths.get(fileNameWithFullPath);
String directory = path.getParent().toString();

You are using File.separator in another line. Why not using it also for your lastIndexOf()?
nativeDir = nativeDir.substring(0, nativeDir.lastIndexOf(File.separator));

File file = new File(path);
String pathWithoutFileName = file.getParent();
where path could be "C:\Users\userName\Desktop\file.txt"

The standard library can handle this as of Java 7
Path pathOnly;
if (file.getNameCount() > 0) {
pathOnly = file.subpath(0, file.getNameCount() - 1);
} else {
pathOnly = file;
}
fileFunction.accept(pathOnly, file.getFileName());

Kotlin solution:
val file = File( "/folder1/folder2/folder3/readme.txt")
val pathOnly = file.absolutePath.substringBeforeLast( File.separator )
println( pathOnly )
produces this result:
/folder1/folder2/folder3

Instead of "/", use File.separator. It is either / or \, depending on the platform. If this is not solving your issue, then use FileSystem.getSeparator(): you can pass different filesystems, instead of the default.

I solve this problem using regex.
For windows:
String path = "";
String filename = "d:\\folder1\\subfolder11\\file.ext";
String regEx4Win = "\\\\(?=[^\\\\]+$)";
String[] tokens = filename.split(regEx4Win);
if (tokens.length > 0)
path = tokens[0]; // path -> d:\folder1\subfolder11

Please try below code:
file.getPath().replace(file.getName(), "");

Related

Test works on local Windows machine but fails on Linux server

I have this test:
#Test
void testHeader() {
String inputFile = ".\\src\\main\\resources\\binaryFile";
MDHeader addHeader = new MDHeader();
try (
InputStream inputStream = new FileInputStream(inputFile);
) {
long fileSize = new File(inputFile).length();
byte[] allBytes = new byte[(int) fileSize];
inputStream.read(allBytes);
ProducerRecord<String, byte[]> record = new ProducerRecord<String, byte[]>("foo", allBytes);
ProducerRecord<String, byte[]> hdr = addHeader.addMDHeader(record);
for (Header header : hdr.headers()) {
assertEquals("mdpHeader", header.key());
}
}
catch(Exception e) {
assert (false);
}
}
The test succeeds when run locally through Eclipse on my Windows desktop but it fails at com.me.be.HeaderTests.testMDHeader(HeaderTests.java:81) when trying to build the jar on a Linux server. That's the line assert (false). I haven't got any more information on the issue yet but was wondering if it could be the backslashes in inputFile in a Linux environment?
Java on Windows and Linux will both accept / as path separator, whereas Linux does not like \\ as a path separator - so treats the whole string as ONE path component, not 4 parts as you'd expect:
String inputFile = "./src/main/resources/binaryFile";
However for file handling it is better to use java.nio.Path or java.io.File in place of String.
WINDOWS
jshell> Path.of("./src/main/resources/binaryFile")
$2 ==> .\src\main\resources\binaryFile
Linux
jshell> Path.of("./src/main/resources/binaryFile")
$1 ==> ./src/main/resources/binaryFile
You can also use Path.of without any file separator for any OS:
Path p = Path.of("src","main","resources","binaryFile");
The File.separator string is handy to concat into the path string in order to produce an OS independent file path.
String inputFile = "." + File.separator + "src" + File.separator + "main" + File.separator + "resources" + File.separator + "binaryFile";
Should give you a cross platform compliant file path.

Fortify pointed out an issue: "Portability Flaw: File Separator", but there is no hard-coded separator in the code

Fortify SCA tool find an issue called Portability Flaw: File Separator, but with the source of those issues, there is none hardcoded file separator such as "/" or "\", only file extensions such as "." exists.
Our customer used Fortify SCA to scan their legacy system source codes. Fortify found Portability Flaw: File Separator issues. It said that the file names which declared in a String array contain hard-coded file separator (this string array is the source of the problem), but I can't see any file separator such as "/" or "\" in those file name strings.
public static final String SYS_SPRAT = File.separator; //this is declared as a class attribute
String[] fileNames = { //fortify points out here is the source of this issue
"",
"2.5.1aaaaa.pdf",
"2.5.2bbbbb.pdf",
"2.5.3ccccc.pdf",
.......
"5.1.4甲甲甲甲甲.pdf",
};
String fileName = null;
File file = null;
int iParam = Integer.parseInt(sParam);
if (iParam >= 1 && iParam <= 26) {
fileName = fileNames[iParam];
String filePath = SYS_SPRAT + "home" + SYS_SPRAT + "xxx" + SYS_SPRAT + "ooo" + SYS_SPRAT + "Resource" + SYS_SPRAT + fileName;
file = new File(filePath);
else {
addFacesMessage("wrong parameter");
return null;
}
I still can't figure out why there is an issue. Is it a false positive? (but why?)
It seems that Fortify may be overly strict here. Even their website says that using File.separator like this should be ok.
I can't see any portability problem using File.separator. Even on OpenVMS systems, where file paths are in the format devicename:[directory.subdirectory]file.ext;version, the Java runtime internally translates between a / separator and the proper VMS format.
First, double-check using a "Find" tool that you don't have any \ or / characters in any of the strings in filenames[] (don't just rely on visual inspection). If there is definitely no such character, then proceed with the suggestion below.
Try avoiding File.separator altogether. Instead, try using Paths.get:
public static final Path RESOURCE_DIR = Paths.get(
"home", "xxx", "ooo", "Resource");
String[] fileNames = {
"",
"2.5.1aaaaa.pdf",
"2.5.2bbbbb.pdf",
"2.5.3ccccc.pdf",
.......
"5.1.4甲甲甲甲甲.pdf",
};
String fileName = null;
File file = null;
int iParam = Integer.parseInt(sParam);
if (iParam >= 1 && iParam <= 26) {
fileName = fileNames[iParam];
file = RESOURCE_DIR.resolve(filePath).toFile();
else {
addFacesMessage("wrong parameter");
return null;
}
Is Fortify ok when you do this?

How to extract part of file name of a CSV file in Java

I have a CSV file and I want to extract part of the file name using Java code.
For example if the name of the file is --> StudentInfo_Mike_Brown_Log.csv
I want to be able to just extract what is between the first two _'s in the file name. Therefore in this case I would be extracting Mike
So far I am doing the following:
String fileName = "C:\\User\\StudentInfo_Mike_Brown_Log.csv";
File file = new File(fileName);
String extractedInfo= fileName.substring(fileName.indexOf("_"), fileName.indexOf("."));
System.out.println(extractedInfo);
This code currently gives me _Mike_Brown_brown_Log but I want to only print out Mike.
You can use split with a Regex to split the String into substrings.
Here is an example:
final String fileName = "C:\\User\\StudentInfo_Mike_Brown_Log.csv";
final String[] split = fileName.split("_");
System.out.println(split[1]);
Try this:
int indexOfFirstUnderscore = fileName.indexOf("_");
int indexOfSecondUnderscore = fileName.indexOf("_", indexOfFirstUnderscore+2 );
String extractedInfo= fileName.substring(indexOfFirstUnderscore+1 , indexOfSecondUnderscore );
System.out.println(extractedInfo);
You could use the getName() method from the File object to return just the name of the file (with extension but without trailing path) and than do a split("_") like #Chasmo mentioned.
E.g.
File input = new File(file);
String fileName = input.getName();
String[] partsOfName = fileName.split("_");
System.out.println(Arrays.toString(partsOfName));
You can use lastIndexOf(), in addition to indexOf():
String fileName = "C:\\User\\StudentInfo_Mike_Brown_Log.csv";
File file = new File(fileName);
filename = file.getName();
String extractedInfo= fileName.substring(
fileName.indexOf("_"),
fileName.lastIndexOf("_"));
System.out.println(extractedInfo);
It is important to firstly call file.getName() so this method does not get confused with underscore '_' characters in the file path.
Hope this helps.
Use indexOf and substring method of String class:
String fileName = "C:\\User\\StudentInfo_Mike_Brown_Log.csv";
int indexOfUnderScore = fileName.indexOf("_");
int indexOfSecondUnderScore = fileName.indexOf("_",
indexOfUnderScore + 1);
if (indexOfUnderScore < 0 || indexOfSecondUnderScore < 0) {
throw new IllegalArgumentException(
"string is not of the form string1_string2_ " + fileName);
}
System.out.println(fileName.substring(indexOfUnderScore + 1,
indexOfSecondUnderScore));
Solved from the previous answer:
String fileName = "C:\\User\\StudentInfo_Mike_Brown_Log.csv";
File file = new File(fileName);
fileName = file.getName();
System.out.println(fileName.split("\\.")[0]);

Get character from string between similar sings

I am trying to get a path of an image in my android device, such as:
/ storage/emulated/0/DCIM/Camera/NAME.jpg
and just trying to grab the image name, but i can.
I am trying with ...
String s = imagePath;
Where the route imagePath
            
s = s.substring (s.indexOf ("/") + 1);
s.substring s = (0, s.indexOf () ".");
Log.e ("image name", s);
it returns me :
storage/emulated/0/DCIM/Camera/NAME.jpg
and i only want
NAME.jpg
You need String.lastIndexOf():
String imagePath = "/path/to/file/here/file.jpg";
String path = imagePath.substring(imagePath.lastIndexOf('/') + 1);
You can do something like that:
File imgFile = new File(imagePath);
String filename = imgFile.getFilename();
This saves you a lot of hassle when you want to use your application cross-platform, because on Linux you have "/" as path delimiters and "\" on Windows
In case, if you are dealing with File object, then you can use its predefined method getName().
i.e.:
File mFile = new File("path of file");
String filename = mFile.getName();

Getting the right slash for each platform

I have a JFilechooser to select a filename and path to store some data. But I also want to store an additional file in the same path, same name but different extension. So:
File file = filechooser.getSelectedFile();
String path = file.getParent();
String filename1 = file.getName();
// Check the extension .ext1 has been added, else add it
if(!filename1.endswith(".ext1")){
filename2 = filename1 + ".ext2";
filename1 += ".ext1";
}
else{
filename2 = filename1;
filename2 = filename2.substring(0, filename2.length-4) + "ext2";
}
// And now, if I want the full path for these files:
System.out.println(path); // E.g. prints "/home/test" withtout the ending slash
System.out.println(path + filename1); // E.g. prints "/home/testfilename1.ext1"
Of course I could add the "/" in the middle of the two strings, but I want it to be platform independent, and in Windows it should be "\" (even if a Windows path file C:\users\test/filename1.ext1 would probably work).
I can think of many dirty ways of doing this which would make the python developer I'm carrying inside cry, but which one would be the most clean and fancy one?
You can use the constants in the File class:
File.separator // e.g. / or \
File.pathSeparator // e.g. : or ;
or for your path + filename1 you can do
File file = new File(path, filename1);
System.out.println(file);
Just use the File class:
System.out.println(new File(file.getParent(), "filename1"));
You can use:
System.getProperty("file.separator");

Categories

Resources