Short c#'s alternative to Java's Path.ResolveSibling. Unpossible? - java

I have a filePath string filePath = #"C:\MyDir\MySubDir\myfile.ext"; and another file name string file2 = "otherfile.txt". Say I would like to get another file path string filePath2 = #"C:\MyDir\MySubDir\otherfile.txt"; .
Is there a method in c# to create such filePath2?
In Java the method is
Path resolveSibling(Path other)
Resolves the given path against this
path's parent path. This is useful where a file name needs to be
replaced with another file name. For example, suppose that the name
separator is "/" and a path represents "dir1/dir2/foo", then invoking
this method with the Path "bar" will result in the Path
"dir1/dir2/bar".

Something like this (combining 1st file's directory name and the 2nd file name):
string filePath = #"C:\MyDir\MySubDir\myfile.ext";
string file2 = "otherfile.txt";
// C:\MyDir\MySubDir\otherfile.txt
string result = Path.Combine(Path.GetDirectoryName(filePath), file2);

Related

How to get sub path from the given file path

I want to get path after given token "html" which is a fix token and file path is below
String token = "html"
Path path = D:\data\test\html\css\Core.css
Expected Output : css\Core.css
below is input folder for the program. and defined as the constant in the code.
public static final String INPUT_DIR = "D:\data\test\html"
which will contains input html, css, js files. and want to copy these files to different location E:\data\test\html\ here so just need to extract sub path after html from the input file path to append it to the output path.
lets say input file are
D:\data\test\html\css\Core.css
D:\data\test\html\css\Core.html
D:\data\test\html\css\Core.js
so want to extract css\Core.css, css\Core.html, css\Core.js to append it to the destination path E:\data\test\html\ to copy it.
Tried below
String [] array = path.tostring().split("html");
String subpath = array[1];
Output : \css\Core.css
which is not expected output expected output is css\Core.css
Also above code is not working for below path
Path path = D:\data\test\html\bla\bla\html\css\Core.css;
String [] array = path.toString().split("html");
String subpath = array[1];
In this case I am getting something like \bla\bla\ which is not
expected.
If you only need the path in the form of a string another solution would be to use this code:
String path = "D:\\data\\test\\html\\css\\Core.css";
String keyword = "\\html";
System.out.println(path.substring(path.lastIndexOf(keyword) + keyword.length()).trim());
You can replace the path with file.getAbsolutePath() as mentioned above.
import java.io.File;
public class Main {
public static void main(String[] args) {
// Create a File object for the directory that you want to start from
File directory = new File("/path/to/starting/directory");
// Get a list of all files and directories in the directory
File[] files = directory.listFiles();
// Iterate through the list of files and directories
for (File file : files) {
// Check if the file is a directory
if (file.isDirectory()) {
// If it's a directory, recursively search for the file
findFile(file, "target-file.txt");
} else {
// If it's a file, check if it's the target file
if (file.getName().equals("target-file.txt")) {
// If it's the target file, print the file path
System.out.println(file.getAbsolutePath());
}
}
}
}
public static void findFile(File directory, String targetFileName) {
// Get a list of all files and directories in the directory
File[] files = directory.listFiles();
// Iterate through the list of files and directories
for (File file : files) {
// Check if the file is a directory
if (file.isDirectory()) {
// If it's a directory, recursively search for the file
findFile(file, targetFileName);
} else {
// If it's a file, check if it's the target file
if (file.getName().equals(targetFileName)) {
// If it's the target file, print the file path
System.out.println(file.getAbsolutePath());
}
}
}
}
}
This code uses a recursive function to search through all subdirectories of the starting directory and print the file path of the target file (in this case, "target-file.txt") if it is found.
You can modify this code to suit your specific needs, such as changing the starting directory or target file name. You can also modify the code to perform different actions on the target file, such as reading its contents or copying it to another location.
Your question lacks details.
Is the "path" a Path or a String?
How do you determine which part of the "path" you want?
Do you know the entire structure of the "path" or do you just have the delimiting part, for example the html?
Here are six different ways (without iterating, as you stated in your comment). The first two use methods of java.nio.file.Path. The next two use methods of java.lang.String. The last two use regular expressions. Note that there are probably also other ways.
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class PathTest {
public static void main(String[] args) {
// D:\data\test\html\css\Core.css
Path path = Paths.get("D:", "data", "test", "html", "css", "Core.css");
System.out.println("Path: " + path);
Path afterHtml = Paths.get("D:", "data", "test", "html").relativize(path);
System.out.println("After 'html': " + afterHtml);
System.out.println("subpath(3): " + path.subpath(3, path.getNameCount()));
String str = path.toString();
System.out.println("replace: " + str.replace("D:\\data\\test\\html\\", ""));
System.out.println("substring: " + str.substring(str.indexOf("html") + 5));
System.out.println("split: " + str.split("\\\\html\\\\")[1]);
Pattern pattern = Pattern.compile("\\\\html\\\\(.*$)");
Matcher matcher = pattern.matcher(str);
if (matcher.find()) {
System.out.println("regex: " + matcher.group(1));
}
}
}
Running the above code produces the following output:
Path: D:\data\test\html\css\Core.css
After 'html': css\Core.css
subpath(3): css\Core.css
replace: css\Core.css
substring: css\Core.css
split: css\Core.css
regex: css\Core.css
I assume you know how to modify the above in order to
I want to get file path after /test

Put Brackets around filename

This is a correction of my previous question Put brackets around filename for Excel formula
My project is based on Apache POI.I'm trying to use a formula on a cell.
My formula is as follows.
sheet7.createRow(0).createCell(0).setCellFormula("+'C:\\Users\\Desktop\\[Test.xlsx]Average_Graph'!A2");
Im using a JFileChooser, which allows users to select the file. Therefore the filepath will be changed every time the program is used.
From the JFileChooser, I'm getting a filepath as follows.
String filepath= "C:\\Users\\Desktop\\Sheet.xlsx"`
In order to work the formula correctly, the filepath should be in following format.
"C:\\Users\\Desktop\\[Sheet.xlsx]"
How Can I Change the string which I'm getting from the JFileCHooser to run the formula correctly?
In previous question, I mistakenly typed C:\Users\Desktop[Sheet.xlsx] instead of C:\Users\Desktop\[Sheet.xlsx]
The answers gave me the output which i've mentioned. But I need the Output as C:\Users\Desktop\[Sheet.xlsx]
Please help.
If you want to solve this by directly altering the file path, you may use String#replaceAll:
String filepath = "C:\\Users\\Desktop\\Sheet.xlsx";
filepath = filepath.replaceAll("(?<=\\\\)([^\\\\]+)$", "[$1]");
System.out.println(filepath);
C:\Users\Desktop\[Sheet.xlsx]
Demo
File names won't have \backslashes in them, so we can assume that our filename begins after the last backslash and ends at the end of the string.
We can use this:
String filepath = "C:\\Users\\Desktop\\Sheet.xlsx";
String dir = filepath.substring(0, filepath.lastIndexOf("\\"+1));
String filename = filepath.substring(filepath.lastIndexOf("\\"+1));
filepath = dir + "[" + filename + "]";
Or a shorter version:
String filepath = "C:\\Users\\Desktop\\Sheet.xlsx";
filepath = filepath.substring(0, filepath.lastIndexOf("\\"+1)) +
"[" + filepath.substring(filepath.lastIndexOf("\\"+1)) + "]";

Resource File Path as String (not streaming)

I don't get it - I'm trying to get the path of a file so that the file (an image) can be included as an attachment in an email.
My system consists of two parts - a web app and a jar. (actually three parts - a common shared jar containing DAOs etc.)
They're both built using maven.
They both contain this image in this path:
src/main/resources/logo_48.png
WebApp:
String logo1 = getClass().getClassLoader().getResource("logo_48.png").getPath();
This works perfectly - both on local (Windows) and Linux
Jar Application:
String logo1 = getClass().getClassLoader().getResource("logo_48.png").getPath(); //doesn't work
I've taken advice from here:
How to access resources in JAR file?
here:
Reading a resource file from within jar
here:
http://www.coderanch.com/t/552720/java/java/access-text-file-JAR
and others
Most answers offer to load the file as a stream etc. but I'm only wishing to get the path assigned to the String. Other resources have led me to hacking the code for hours only to find the end result doesn't work.
After so many instances of /home/kalton/daily.jar!logo_48.png does not exist errors I was frustrated and settled on the following workaround:
Copy the logo_48.png directly to the folder where the jar resides (/home/kalton/)
Alter my jar application code to:
String logo1 = "/home/kalton/logo_48.png";
And it works.
Could anyone show me the right way to get the PATH (as a String) of a file in the resources folder from a JAR that is not unpacked?
This issue was driving me crazy for weeks!
Thanks in advance.
KA.
Adding actual use code of 'path' for clarity of use:
public static MimeMultipart assemble4SO(String logoTop, String emailHTMLText) throws MessagingException, IOException {
MimeMultipart content = new MimeMultipart("related");
String cid = Long.toString(System.currentTimeMillis());
String cidB = cid + "b";
String cssStyle = "";
String body = "<html><head>" + cssStyle + "</head><body><div>" + "<img src='cid:" + cid + "'/>" + emailHTMLText + "<img src='cid:" + cidB + "'/></div></body></html>";
MimeBodyPart textPart = new MimeBodyPart();
textPart.setContent(body, "text/html; charset=utf-8");
content.addBodyPart(textPart);
//add an inline image
MimeBodyPart imagePart = new MimeBodyPart();
imagePart.attachFile(logoTop);
imagePart.setContentID("<" + cid + ">");
imagePart.setDisposition(MimeBodyPart.INLINE);
content.addBodyPart(imagePart);
.............
From the top…
A .jar file is actually a zip file. A zip file is a single file that acts as an archive. The entries in this archive are not separate files, they're just sequences of compressed bytes within the zip file. They cannot be accessed as individual file names or File objects, ever.
Also important: The getPath method of the URL class does not convert a URL to a file name. It returns the path portion of the URL, which is just the part after the host (and before any query and/or fragment). Many characters are illegal in URLs, and need to be “escaped” using percent encoding, so if you just extract the path directly from a URL, you'll often end up with something containing percent-escapes, which therefore is not a valid file name at all.
Some examples:
String path = "C:\\Program Files";
URL url = new File(path).toURI().toURL();
System.out.println(url); // prints file:/C:/Program%20Files
System.out.println(url.getPath()); // prints /C:/Program%20Files
File file = new File(url.getPath());
System.out.println(file.exists()); // prints false, because
// "Program%20Files" ≠ "Program Files"
 
String path = "C:\\Users\\VGR\\Documents\\résumé.txt";
URL url = new File(path).toURI().toURL();
// Prints file:/C:/Users/VGR/Documents/r%C3%A9sum%C3%A9.txt
System.out.println(url);
// Prints /C:/Users/VGR/Documents/r%C3%A9sum%C3%A9.txt
System.out.println(url.getPath());
File file = new File(url.getPath());
System.out.println(file.exists()); // prints false, because
// "r%C3%A9sum%C3%A9.txt" ≠ "résumé.txt"
Based on your edit, I see that the real reason you want a String is so you can call MimeBodyPart.attachFile. You have two options:
Do the work of attachFile yourself:
URL logo = getClass().getLoader().getResource("logo_48.png");
imagePart.setDataHandler(new DataHandler(logo));
imagePart.setDisposition(Part.ATTACHMENT);
Copy the resource to a temporary file, then pass that file:
Path logoFile = Files.createTempFile("logo", ".png");
try (InputStream stream =
getClass().getLoader().getResourceAsStream("logo_48.png")) {
Files.copy(stream, logoFile, StandardCopyOption.REPLACE_EXISTING);
}
imagePart.attachFile(logoFile.toFile());
As you can see, the first option is easier. The second option also would require cleaning up your temporary file, but you don't want to do that until you've sent off your message, which probably requires making use of a TransportListener.

How do I extract subpath neatly accounting for root and no root folders on java

I have a Path object and a String object, the Path object represents part of the starting path represented by the filename
e.g for the filename /Music/Beatles/Help.mp3 the Path object may be
/
/Music
/Music/Beatles
this simple method returns the part of the path minus the basefolder
public String getPathRemainder(Path path, String filename)
{
if(baseFolder.getNameCount()==0)
{
return song.getFilename().substring(baseFolder.toString().length());
}
else
{
return song.getFilename().substring(baseFolder.toString().length()+File.separator.length());
}
i.e
Music/Beatles/Help.mp3
Beatles/Help.mp3
Help.mp3
but although simple its rather messy as I have to account for the fact that if the base folder is a root folder it ends with '/' (on unix) but not none root paths.
Im sure there is a neater approach, but I cant see it.
Using java.nio available since Java 7:
Path file = Paths.get("/Music/Beatles/Help.mp3");
Path dir1 = Paths.get("/");
Path dir2 = Paths.get("/Music");
Path dir3 = Paths.get("/Music/Beatles");
System.out.println(dir1.relativize(file));
System.out.println(dir2.relativize(file));
System.out.println(dir3.relativize(file));
You get:
Music/Beatles/Help.mp3
Beatles/Help.mp3
Help.mp3

merging two strings to shape a file path

assuming that we have a folder with path:
path="C:\\Users\\me\\Desktop\\here"
also, consider a File[] named readFrom has different files. as an example, consider following path which refering to a file:
C:\\Users\\me\\Desktop\\files\\1\\sample.txt"
my question is, how can i have a string with following value:
String writeHere= "C:\\Users\\me\\Desktop\\here\\files\\1\\sample.txt"
EDIT
I should have mentioned that this path is unknown, we need first to read a file and get its path then write it into another folder, so for the path of writing I need writeHere as input. in conclusion , the answer should contains the way to get the path from the file too.
String s1="C:\\Users\\me\\Desktop\\here";
String s2="C:\\Users\\me\\Desktop\\files\\1\\sample.txt";
String s3=s2.substring(s2.indexOf("\\files"));
System.out.println(s1+s3);
OUTPUT
C:\Users\me\Desktop\here\files\1\sample.txt
To get Absolute Path of file
File f=new File("C:\\Users\\me\\Desktop\\files\\1\\sample.txt");
System.out.println(f.getAbsolutePath());
Split the into arrays and merge the path with split-ted string
String path="C:\\Users\\me\\Desktop\\here";
String [] splt = yourPath.split("\\");
finalPath = path + "\\" + splt[3] + "\\" + splt[4] + "\\" + splt[5];
yourPath is the path refering to a file
Changing the folder's path
File afile =new File("C:\\Users\\me\\Desktop\\files\\1\\sample.txt");
afile.renameTo(new File(finalPath))
If you just need the String and do not need to read the file, use string concatenation with is just str1 + str2. If you need the File object create a base File object on the initial path and then two new File objects from that:
File path = new File("C:\\Users\\me\\Desktop\\here");
String[] files = { "files\\1\\sample.txt", "files\\3\\this.avi" };
for (filename in files) {
File f = new File(path, filename);
...
}
Oh, I think I see better what you want to do. You want to "reparent" the files:
// Note:
// newParent I assume would be a parameter, not hardcoded
// If so, there is no hardcoding of the platform specific path delimiter
// the value, start, is also assumed to be a parameter
File newParent = new File("C:\\Users\\me\\Desktop\\here");
File[] readFrom = ...;
for (File f in readFrom) {
String[] parts = f.list();
String[] needed = Arrays.copyOfRange(parts, start, parts.length);
File newFile = new File(newParent);
for (String part in needed) {
newFile = new File(newFile, part);
}
...
}
I think you could do something like:
String name = "Rafael";
String lastname = " Nunes";
String fullname = name + lastname;
Here you can see the string concatenation working, and you can often visit the Java documentation.

Categories