I want to be able to use a variable that can be changed within a file path. The username relevant to the file path is declared in the constructor then I have tried to assign this to the file path in the below method.
What I wanted to happen when calling:
System.out.format("%s%n", documentsPath.resolve(username +"\\Documents"));
Was that the documents Path would then be:
C:\Users\ryanb\Documents
Instead when I call documentsPath.toString() I only get returned:
C:\Users\
How do I get the documentsPath variable to be assigned with the String username and the "\\Documents" at the end.
This is my code:
class profileCopy{
/*global variables */
private Path documentsPath;
private Path desktopPath;
private Path favoritesPath;
private Path networkFolder;
private String username;
private String foldername;
public profileCopy(String username, String foldername)
{
this.username = username;
this.foldername = foldername;
documentsPath = Paths.get("C:\\Users");
desktopPath = Paths.get("C:\\Users");
favoritesPath = Paths.get("C:\\Users");
networkFolder = (Paths.get("F:\\Data\\WP51"));
}
public void copyDocumentsFolder() throws IOException
{
Path newDir = Paths.get("C:\\Users\\ryanb\\Documents\\TestCopy");
System.out.format("%s%n", documentsPath.resolve(username +"\\Documents"));
System.out.format("%s%n", networkFolder.resolve(foldername + "\\Backup"));
System.out.println(networkFolder.getFileName());
Files.move(documentsPath, networkFolder.resolve(documentsPath.getFileName()));
System.out.println(newDir.toString());
}
The main point in order to your code doesn't work is that you don't re-assign the return value of resolve() method to your path variable, since the method returns a new object.
In order to build your Paths, you can use something like this:
documentsPath = Paths.get(string.format("C:\\Users\\%s\\%s", username, "Documents");
If you want to reuse some code, you can use an array of folders and create them:
List<Path> paths = new ArrayList();
String[] defaultFolders = {"Documents", "Desktop", "Music"};
foreach (folder : defaultFolders) {
paths.add(Path.get(string.format("C:\\Users\\%s\\%s", username, folder)));
PS: Since you're developing that in java, you should consider to make the Path's UNIX or Windows Compatible, since UNIX environments doensn't recognize the "C:/Users" path.
The resolve methods returns a Path
public void copyDocumentsFolder() throws IOException
{
Path newDir = Paths.get("C:\\Users\\ryanb\\Documents\\TestCopy");
documentsPath = documentsPath.resolve(username + "\\Documents");
networkFolder = networkFolder.resolve(foldername + "\\Backup");
System.out.format("%s%n", documentsPath);
System.out.format("%s%n", networkFolder);
System.out.println(networkFolder.getFileName());
Files.move(documentsPath, networkFolder.resolve(documentsPath.getFileName()));
System.out.println(newDir.toString());
}
Related
I have the following prefix:
String prefix = TemplatesReader.class.getClassLoader().getResource("templates/").getPath();
and have method
public byte[] read(String pathToTemplate) {
return Files.readAllBytes(Paths.get(prefix + pathToTemplate));
}
in intellij idea works correctly, but when starting jar an error occurs:
java.nio.file.NoSuchFileException: file:/app.jar!/BOOT-INF/classes!/templates/request-orders/unmarked/RequestOrderUnmarked.pdf
You must not assume that a resource is a file. When the resource is inside a .jar file, it is a part of that .jar file; it is no longer a separate file at all.
You cannot use Files or Paths to read the resource.
You cannot use the getPath() method of URL. It does not return a file name. It only returns the path portion of the URL (that is, everything between the URL’s scheme/authority and its query portion), which is not a file path at all.
Instead, read the resource using getResourceAsStream:
private static final String RESOURCE_PREFIX = "/templates/";
public byte[] read(String pathToTemplate)
throws IOException {
try (InputStream stream = TemplatesReader.class.getResource(
RESOURCE_PREFIX + pathToTemplate)) {
return stream.readAllBytes();
}
}
This articles describes how to generate and import a PDOM index.
After invoking the generation application GeneratePDOM I got a pdom file /home/sadik/eclipse-2019-06/eclipse/pdomExample.pdom. But I have problem importing the file.
The command to generate is this:
java -jar plugins/org.eclipse.equinox.launcher_1.5.400.v20190515-0925.jar -application "org.eclipse.cdt.core.GeneratePDOM" -target /home/sadik/eclipse-2019-06/eclipse/pdomExample.pdom -source /home/sadik/my-plugin-runtime-2019-06/CDTTest_Local/ -id cdttest_01 -indexer org.eclipse.cdt.core.myfastIndexer
Note the target and source arguments.
To test the import I wrote a class that implements IReadOnlyPDOMProvider
public class MyReadOnlyPDOMProvider implements IReadOnlyPDOMProvider {
public MyReadOnlyPDOMProvider() {
System.out.println("PDOMProvider");
}
#Override
public boolean providesFor(ICProject project) throws CoreException {
return true;
}
#Override
public IPDOMDescriptor[] getDescriptors(ICConfigurationDescription config) {
final IPath fileBase = Path.fromOSString("/home/sadik/eclipse-2019-06/eclipse/");
final IPath projectBase = Path.fromOSString("/home/sadik/my-plugin-runtime-2019-06/CDTTest_Local/");
return new IPDOMDescriptor[] { new IPDOMDescriptor() {
public IIndexLocationConverter getIndexLocationConverter() {
return new URIRelativeLocationConverter(URIUtil.toURI(projectBase));
}
public IPath getLocation() {
IPath path = fileBase.append("pdomExample.pdom");
return path;
}
}};
}
Are the paths correct? I actually don't know what location is supposed to be returned here.
I defined that class in the CDT extension point CIndex in my Plugin's plugin.xml:
<extension
point="org.eclipse.cdt.core.CIndex">
<ReadOnlyPDOMProvider
class="de.blub.plugin.MyReadOnlyPDOMProvider">
</ReadOnlyPDOMProvider>
</extension>
I'm testing with this file (/home/sadik/my-plugin-runtime-2019-06/CDTTest_Local/tests/indexer/usage.cc):
#include <declaration.h>
int main() {
int a = testThis();
}
When I right click testThis() and chose go to declaration, I expect to go to the function declaration in /home/sadik/my-plugin-runtime-2019-06/CDTTest_Local/tests/indexer/declaration.h. Both files are located in the same directory.
But what happens is that an editor is opened with an empty file. The editor even tells me the path: /home/soezoguz/rtt-plugin-runtime-2019-06/tests/indexer/declaration.h.
The path is missing the project name. So I guess the pdom file stores locations below the specified source directory. How can I tell the PDOMProvider to look into the correct directory for the indexed files?
For some reason the trailing "/" has been ommited by URIUtil.toURI(...). But in the description of URIRealtiveLocationConverter it says
Note: The supplied base URI must end with a forward slash
So I create an URI instance from String and append a "/" to the String.
#Override
public IPDOMDescriptor[] getDescriptors(ICConfigurationDescription config) {
final IPath fileBase = Path.fromOSString("/home/sadik/eclipse-2019-06/eclipse/");
final IPath projectBase = config.getProjectDescription().getProject().getFullPath();
return new IPDOMDescriptor[] { new IPDOMDescriptor() {
public IIndexLocationConverter getIndexLocationConverter() {
URI baseURI;
try {
baseURI = new URI(projectBase.toString()+"/");
return new URIRelativeLocationConverter(baseURI);
} catch (URISyntaxException e) {
e.printStackTrace();
}
baseURI = URIUtil.toURI(projectBase);
return new URIRelativeLocationConverter(URIUtil.toURI(projectBase));
}
public IPath getLocation() {
IPath path = fileBase.append("pdomExample.pdom");
return path;
}
}};
}
Consider the code sample below. Migrator class takes two input files, processes it and writes the output to final.tbl.
I want final.tbl to be created on the same path where the folder of input files is present.
Also the execute method should take relative path of this generated final.tbl file.
public class Migrator{
public void Migrate(String path1,String path2){
PrintStream out = new PrintStream("final.tbl");//I need relative path as that of input folder path i.e path1,path2
//.....
//.....Processing
}
}
class MainProcess{
public execute(String path){
//here the execute method should the the relative path of above final.tbl file
}
public static void main(String args[]){
}
}
Path path = Paths.get(path1);
PrintStream out = new PrintStream(path.getParent().toString() + "\\final.tbl");
I think you can use getAbsolutePath to get path to your input files:
public class Migrator{
public void Migrate(String path1,String path2){
File f = new File(path1);
String absolutePath = f.getAbsolutePath(); // use absolutePath for your PrintStream
PrintStream out = new PrintStream(absolutePath);//I need relative path as that of input folder path i.e path1,path2
//.....
//.....Processing
}
}
Hope it helped
Use the getParentFile()
File target = new File(new File(path1).getParentFile(), "final.tbl");
PrintStream out = new PrintStream(target);
I'm trying to achieve a way to obtain the base path of the current classloader when runnning from within a jar.
I mean programatically, I already know it should have the shape of "jarPath+jarFile.jar!/"
Unlike file system's call, getResource(".") or .getResource("/") do not work from inside the jar.
Ideally it should be an abstract solution for any file provider, so something like:
Path BASE_PATH = Paths.get(...getResource("").toURI())
which could return the correct root path for both jars and file system so I can use relative urls to my resources without having to do any conditional statements and url manual string parsing/build.
You should be able to find out the path of the jar and or target folder containing you class or any resource by using this code:
package com.stackoverflow.test;
import java.net.URL;
import java.nio.file.Paths;
public class ClassPathUtils {
public static String getBasePath(String jarPath) {
String path = getJarPathFromClass(jarPath);
if (path == null) {
return null;
}
if (path.startsWith("jar:")) {
path = path.substring("jar:".length());
}
if (path.startsWith("file:")) {
path = path.substring("file:".length());
}
if (path.endsWith(jarPath)) {
path = path.substring(0, path.length()-jarPath.length());
}
return path;
}
public static String getBasePath(Class clazz) {
return getBasePath(classNameDotClass(clazz));
}
private static String classNameDotClass(Class clazz) {
return clazz.getName().replaceAll("\\.", "/") + ".class";
}
private static String getJarPathFromClass(String resource) {
final URL url = ClassPathUtils.class.getClassLoader().getResource(resource);
return url == null ? null : url.toString();
}
public static void main(String[] args) {
//System.out.println(Paths.get(ClassPathUtils.getBasePath("."))); // doesn't work in a jar
System.out.println(Paths.get(ClassPathUtils.getBasePath(ClassPathUtils.class)));
System.out.println(Paths.get(ClassPathUtils.getBasePath("fonts/atcitadelscript.ttf"))); // any classpath resource
System.out.println(Paths.get(ClassPathUtils.getBasePath(String.class))); // actually finds rt.jar
}
}
If you run this code from your IDE, or from maven, it will give you the paths to target/classes for your own resources, or the path to a jar for other resources (E.g. String.class).
If you call it from a jar, it will always tell you the path of the jar file.
run from IDE:
/home/alexander/projects/stackoverflow/stuff/target/classes
/home/alexander/projects/stackoverflow/stuff/target/classes
/usr/lib/jvm/java-7-openjdk-amd64/jre/lib/rt.jar!`
run from JAR:
/home/alexander/projects/stackoverflow/stuff/target/test-stuff-0.1-SNAPSHOT.jar!
/home/alexander/projects/stackoverflow/stuff/target/test-stuff-0.1-SNAPSHOT.jar!
/usr/lib/jvm/java-7-openjdk-amd64/jre/lib/rt.jar!
Is that what you're looking for?
I'm using apache's FileUpload in order to upload some files to my webserver. Problem is I don't want to upload them to a specific location on the machine i.e : c:\tmp, but rather to a relative path such as /ProjectName/tmp/
Here's my code:
private static final long serialVersionUID = 1L;
private String TMP_DIR_PATH = "c:\\tmp";
private File tmpDir;
private static final String DESTINATION_DIR_PATH ="/files";
private File destinationDir;
public void init(ServletConfig config) throws ServletException {
super.init(config);
tmpDir = new File(TMP_DIR_PATH);
if(!tmpDir.isDirectory()) {
throw new ServletException(TMP_DIR_PATH + " is not a directory");
}
String realPath = getServletContext().getRealPath(DESTINATION_DIR_PATH);
destinationDir = new File(realPath);
if(!destinationDir.isDirectory()) {
throw new ServletException(DESTINATION_DIR_PATH+" is not a directory");
}
}
I want to change TMP_DIR_PATH so it's relative to my project, help would be appreciated!
If your actual concern is the hardcoding of the c:\\tmp part which makes the code unportable, then consider using File#createTempFile() instead. This will create the file in the platform default temp location as specified by the java.io.tmpdir system property.
File file = File.createTempFile("upload", ".tmp");
OutputStream output = new FileOutputStream(file);
// ...
If you want the temp directory to be relative to your project you'll have to use getRealPath and then make sure you create the directory if it doesn't already exist.
You can also use File dir = (File) getServletContext().getAttribute("javax.servlet.context.tempdir"); to fetch an app-specific temp directory provided by the container.