replace domainName with folder path using java - java

I am trying to replace apache image path to linux ubuntu folder path while retrieving file path from DB.
http://test.mydomain.com/MainFolder/subFolder/image1.jpg
should be
/var/www/MainFolder/subFolder/image1.jpg
here MainFolder is static folder. so how can i replace "http://test.mydomain.com/" to "/var/www/" where before MainFolder/

You can get domain part of url and replace that part of string like below way..
String imageURL = "http://test.mydomain.com/MainFolder/subFolder/image1.jpg";
String domainPart = getDomainPart(imageURL);
String folderPath = imageURL.replace(domainPart, "/var/www");
public String getDomainPart(String url) {
URI uri = new URI(url);
String scheme = uri.getScheme();
String hostname = uri.getHost();
String domainPart = scheme + "://" + hostname;
return domainPart;
}

Related

how to include path in string array with the file in android

am working with Bitmap.decodeFile(pathname,bOptions), I wanted to include the file detected by the phone in the mean time am using this one
String path = Environment.getExternalStorageDirectory().toString() + "/Pictures/Temp Images";
this is only single one of string and I can't include in my array, I want to do is to pass the parameter to my method which is accepting String[] files which includes the pathFile + filename
ex: sd0/pictures/temp file/img1.jpeg
Supossing you have a variable where the file name is stored:
String path = Environment.getExternalStorageDirectory().toString() + "/Pictures/Temp Images" + File.separator + fileName;
public String getPath(String folderName, String fileName){
return Environment.getExternalStorageDirectory().toString() + folderName + File.separator + fileName;
}
using the method:
String path = getPath("/Pictures/Temp Images", "img1.jpeg");
or
String path = getPath("/Pictures/Temp Images", fileName);

How to split a file path with path and name seperated

How do we split a file path for example
String path=file:\C:\Users\id\work\target\test-classes\ean\sample.txt
to
String filePath=file:\C:\Users\id\work\target\test-classes\ean\
String filename=sample.txt
The functionality required is to use
Paths.get(filePath,filename)
You can use file.getParent() to get the directory path.
And file.getName() to get the file name.
If you create a FileInfo object from your file (add using System.IO)
you can use the FullName property with Replace() to get the path, and the Name property for the name.
using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using System.IO;
namespace Generic_Unit_Tests
{
[TestClass]
public class FileAndPathTest
{
[TestMethod]
public void GetFileNameAndPathTest()
{
string fullFileName = #"C:\Users\joey\Documents\Visual Studio 2012\Projects\Repo Docs and Notes\TestFile.txt";
string filePath = string.Empty;
string fileName = string.Empty;
FileInfo fi = new FileInfo(fullFileName);
filePath = fi.FullName.Replace(fi.Name, string.Empty);
fileName = fi.Name;
Console.WriteLine(string.Format("Path: {0}", filePath));
Console.WriteLine(string.Format("File Name: {0}", fileName));
}
}
}
And the result:
Test Name: GetFileNameAndPathTest
Test Outcome: Passed
Result StandardOutput:
Path: C:\Users\joey\Documents\Visual Studio 2012\Projects\Repo Docs and Notes\
File Name: TestFile.txt
And Bob's your uncle.
Joey

Create folder in a relative path outside the project

How can i save a file to a relative path outside my project ? So i can create a folder of resources on any computer the program runs on?
I tried:
String folderPath=getClass().getClassLoader().getResource(".").getPath()+other stuff
to create a folder path where i save images. It creates a me a folder like tomcat%20v7.0 where indeed my images are saved. I keep absolute path for every picture in my database and then load them in a jsp file. When running the app in eclipse, everything works fine. When trying to run in browser, photos aren't shown.
Browser are installed on C: and tomcat/eclipse on E:
public static List<String> getEndPoints() throws
MalformedObjectNameException,
NullPointerException, UnknownHostException,
AttributeNotFoundException, InstanceNotFoundException,
MBeanException, ReflectionException {
MBeanServer mbs = ManagementFactory.getPlatformMBeanServer();
Set<ObjectName> objs = mbs.queryNames(new ObjectName(
"*:type=Connector,*"), Query.match(Query.attr("protocol"),
Query.value("HTTP/1.1")));
String hostname = InetAddress.getLocalHost().getHostName();
InetAddress[] addresses = InetAddress.getAllByName(hostname);
ArrayList<String> endPoints = new ArrayList<String>();
for (Iterator<ObjectName> i = objs.iterator(); i.hasNext();) {
ObjectName obj = i.next();
String scheme = mbs.getAttribute(obj, "scheme").toString();
String port = obj.getKeyProperty("port");
for (InetAddress addr : addresses) {
String host = addr.getHostAddress();
String ep = scheme + "://" + host + ":" + port;
endPoints.add(ep);
}
}
return endPoints;
}
//use above code to get path like "http://yourip:yourport/yourwebapppath"

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

Remove filename from a URL/Path in 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(), "");

Categories

Resources