merging two strings to shape a file path - java

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.

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

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

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

Java - Getting file name without extension from a folder

I'm using this code to get the absolute path of files inside a folder
public void addFiles(String fileFolder){
ArrayList<String> files = new ArrayList<String>();
fileOp.getFiles(fileFolder, files);
}
But I want to get only the file name of the files (without extension). How can I do this?
i don't think such a method exists. you can get the filename and get the last index of . and truncate the content after that and get the last index of File.separator and remove contents before that.
you got your file name.
or you can use FilenameUtils from apache commons IO and use the following
FilenameUtils.removeExtension(fileName);
This code will do the work of removing the extension and printing name of file:
public static void main(String[] args) {
String path = "C:\\Users\\abc\\some";
File folder = new File(path);
File[] files = folder.listFiles();
String fileName;
int lastPeriodPos;
for (int i = 0; i < files.length; i++) {
if (files[i].isFile()) {
fileName = files[i].getName();
lastPeriodPos = fileName.lastIndexOf('.');
if (lastPeriodPos > 0)
fileName = fileName.substring(0, lastPeriodPos);
System.out.println("File name is " + fileName);
}
}
}
If you are ok with standard libraries then use Apache Common as it has ready-made method for that.
There's a really good way to do this - you can use FilenameUtils.removeExtension.
Also, See: How to trim a file extension from a String
String filePath = "/storage/emulated/0/Android/data/myAppPackageName/files/Pictures/JPEG_20180813_124701_-894962406.jpg"
String nameWithoutExtension = Files.getNameWithoutExtension(filePath);

Remove whitespace from all filenames in directory - Java

I have directory of images and I want to rename the files by removing all of the whitespace in the name.
So let's say I have a file name called " f il ena me .png" (I plan on checking all of the file names in the directory). How might I remove all of the spaces and rename the image so that the correct file name (for this specific case) is "filename.png".
So far I have tried the following code and it actually deletes the image in the directory (I'm testing it on one image in the directory currently).
public static void removeWhiteSpace (File IBFolder) {
// For clarification:
// File IBFolder = new File("path/containing/images/folder/here");
String oldName;
String newName;
String temp;
for (File old : IBFolder.listFiles()) {
oldName = old.getName();
temp = oldName.replaceAll(" ", "");
// I have also tried:
// temp = oldName.replaceAll("//s", "");
temp = temp.split(".png")[0];
newName = temp + ".png";
System.out.println(newName);
old.renameTo(new File(newName));
}
}
I think it doesn't delete the images, but moves them to your current working directory and renames it to newName, but since newName is missing a path information, it will rename / move it to "./" (from wherever you run your program).
I think you have a bug in these lines:
temp = temp.split(".png")[0];
newName = temp + ".png";
"." is a wilcard character and lets say your file is called "some png.png", newName would be "som.png", because "some png.png".replaceAll(" ", "").split(".png") results in "som".
If by any reason you need the String.split() method, please properly quote the ".":
temp = temp.split("\\.png")[0];
Ignoring naming conventions (which I intend to fix later) here is the solution I finalized.
public static void removeWhiteSpace (File IBFolder) {
// For clarification:
// File IBFolder = new File("path/containing/images/folder/here");
String oldName;
String newName;
for (File old : IBFolder.listFiles()) {
oldName = old.getName();
if (!oldName.contains(" ")) continue;
newName = oldName.replaceAll("\\s", "");
// or the following code should work, not sure which is more efficient
// newName = oldName.replaceAll(" ", "");
old.renameTo(new File(IBFolder + "/" + newName));
}
}

How to create multiple directories given the folder names

I have a list of files, the names of these files are are made of a classgroup and an id (eg. science_000000001.java)
i am able to get the names of all the files and split them so i am putting the classgroups into one array and the ids in another.. i have it so that the arrays cant have two of the same values.
This is the problem, i want to create a directory with these classgroups and ids, an example:
science_000000001.java would be in science/000000001/science_000000001.java
science_000000002.java would be in science/000000002/science_000000002.java
maths_000000001.java would be in maths/000000001/maths_000000001.java
but i cannot think of a way to loop through the arrays correctly to create the appropriate directories?
Also i am able to create the folders myself, its just getting the correct directories is the problem, does anyone have any ideas?
Given:
String filename = "science_000000001.java";
Then
File fullPathFile = new File(filename.replaceAll("(\\w+)_(\\d+).*", "$1/$2/$0"));
gives you the full path of the file, in this case science/000000001/science_000000001.java
If you want to create the directory, use this:
fullPathFile.getParentFile().mkdirs();
The above answer is really good for creating new files with that naming convention. If you wanted to sort existing files into their relative classgroups and Ids you could use the following code:
public static void main(String[] args) {
String dirPath = "D:\\temp\\";
File dir = new File(dirPath);
// Get Directory Listing
File[] fileList = dir.listFiles();
// Process each file
for(int i=0; i < fileList.length; i++)
{
if(fileList[i].isFile()) {
String fileName = fileList[i].getName();
// Split at the file extension and the classgroup
String[] fileParts = fileName.split("[_\\.]");
System.out.println("One: " + fileParts[0] + ", Two: " + fileParts[1]);
// Check directory exists
File newDir = new File(dirPath + fileParts[0] + "\\" + fileParts[1]);
if(!newDir.exists()) {
// Create directory
if(newDir.mkdirs()) {
System.out.println("Directory Created");
}
}
// Move file into directory
if(fileList[i].renameTo(new File(dirPath + fileParts[0] + "\\" + fileParts[1] + "\\" + fileName))) {
System.out.println("File Moved");
}
}
}
}
Hope that helps.

Categories