Java относительный путь jar

Как определить относительный путь в Java

here is the structure of my project

Мне нужно прочитать config.properties внутри MyClass.java . Я попытался сделать это с относительным путем следующим образом:

// Code called from MyClass.java File f1 = new File("..\\..\\..\\config.properties"); String path = f1.getPath(); prop.load(new FileInputStream(path)); 

Это дает мне следующую ошибку:

..\..\..\config.properties (The system cannot find the file specified) 

Как я могу определить относительный путь в Java? Я использую JDK 1.6 и работаю на Windows.

ОТВЕТЫ

Ответ 1

Попробуйте что-то вроде этого

String filePath = new File("").getAbsolutePath(); filePath.concat("path to the property file"); 

Итак, ваш новый файл указывает на путь, в котором он создан, обычно в домашней папке вашего проекта.

 String basePath = new File("").getAbsolutePath(); System.out.println(basePath); String path = new File("src/main/resources/conf.properties") .getAbsolutePath(); System.out.println(path); 

Оба дают одинаковое значение.

Ответ 2

 File f1 = new File("..\\..\\..\\config.properties"); 

этот путь, пытающийся получить доступ к файлу, находится в каталоге Project, а затем просто получает доступ к этому файлу.

File f=new File("filename.txt"); 

если ваш файл находится в OtherSources/Resources

this.getClass().getClassLoader().getResource("relative path");//-> relative path from resources folder 

Ответ 3

Во-первых, посмотрите на разницу между абсолютным и относительным путями здесь:

Абсолютный путь всегда содержит корневой элемент и полный список каталогов, необходимых для поиска файла.

Кроме того, относительный путь должен быть объединен с другим путем для доступа к файлу.

В конструкторе File (String pathname) класс Javadoc File сказал, что

Имя пути, будь то абстрактное или строковое, может быть абсолютным или относительным.

Если вы хотите получить относительный путь, вы должны определить путь от текущего рабочего каталога до файла или каталога. Попробуйте использовать системные свойства, чтобы получить это. Как изображения, которые вы нарисовали:

String localDir = System.getProperty("user.dir"); File file = new File(localDir + "\\config.properties"); 

Более того, вам следует избегать использования аналогичных символов «.», «../», «/» и других аналогичных по отношению к относительному пути расположения файлов, поскольку при перемещении файлов их сложнее обрабатывать.

Ответ 4

Стоит отметить, что в некоторых случаях

File myFolder = new File("directory"); 

не указывает на корневые элементы. Например, когда вы размещаете приложение на диске C: ( C:\myApp.jar ), тогда myFolder указывает на (windows)

Ответ 5

 public static void main(String[] args) < Properties prop = new Properties(); InputStream input = null; try < File f=new File("config.properties"); input = new FileInputStream(f.getPath()); prop.load(input); System.out.println(prop.getProperty("name")); >catch (IOException ex) < ex.printStackTrace(); >finally < if (input != null) < try < input.close(); >catch (IOException e) < e.printStackTrace(); >> > > 

Вы также можете использовать Path path1 = FileSystems.getDefault(). getPath (System.getProperty( «user.home» ), «downloads», «somefile.txt» );

Ответ 6

У меня возникли проблемы с прикреплением скриншотов к ExtentReports с использованием относительного пути к моему файлу изображения. Мой текущий каталог при выполнении «C:\Eclipse 64-bit\eclipse\workspace\SeleniumPractic». При этом я создал папку ExtentReports для файла report.html и image.png, как показано ниже.

private String className = getClass().getName(); private String outputFolder = "ExtentReports\\"; private String outputFile = className + ".html"; ExtentReports report; ExtentTest test; @BeforeMethod // initialise report variables report = new ExtentReports(outputFolder + outputFile); test = report.startTest(className); // more setup code @Test // test method code with log statements @AfterMethod // takeScreenShot returns the relative path and filename for the image String imgFilename = GenericMethods.takeScreenShot(driver,outputFolder); String imagePath = test.addScreenCapture(imgFilename); test.log(LogStatus.FAIL, "Added image to report", imagePath); 

Это создает отчет и изображение в папке ExtentReports, но когда отчет открывается и проверяется (пустое) изображение, наведите указатель мыши на изображение. src показывает «Не удалось загрузить изображение» src= «.\ExtentReports\QXKmoVZMW7. PNG».

Это решается путем префикса относительного пути и имени файла для изображения с помощью свойства System «user.dir». Таким образом, это работает отлично, и изображение появляется в отчете html.

String imgFilename = GenericMethods.takeScreenShot(driver,System.getProperty("user.dir") + "\\" + outputFolder); String imagePath = test.addScreenCapture(imgFilename); test.log(LogStatus.FAIL, "Added image to report", imagePath); 

Ответ 7

Пример для Spring Boot. Мой WSDL файл находится в разделе «Ресурсы» в папке «wsdl». Путь к WSDL файлу:

Чтобы получить путь от какого-либо метода к этому файлу, вы можете сделать следующее:

String pathToWsdl = this.getClass().getClassLoader(). getResource("wsdl\\WebServiceFile.wsdl").toString(); 

Ответ 8

Я не собираюсь отвечать на ваш вопрос напрямую, но хочу предложить вам использовать Maven Standard Layout.

Это стандарт Java для организации вашего кода для людей и инструментов сборки.

── maven-project ├───pom.xml └───src ├───main │ ├───java │ ├───resources └───test ├───java └───resources 

Источник

Relative Path in Java

Relative Path in Java

  1. Define a Relative Path to Locate File in Java
  2. Define Relative Path for Parent Directory in Java
  3. Define Relative Path in Current Directory in Java
  4. Define Relative Path Using the ../../ Prefix in Java

This tutorial introduces how to define a relative path in Java.

A relative path is an incomplete path (absence of root directory) and combined with the current directory path to access the resource file. The relative path doesn’t start with the root element of the file system.

We use the relative path to locate a file in the current directory or parent directory, or the same hierarchy.

There are several ways to define a relative path, such as ./ to refer to current directory path, ../ to immediate parent directory path, etc. Let’s see some examples.

Define a Relative Path to Locate File in Java

We can use the relative path to locate a file resource in the current working directory. See the example below.

import java.io.File; public class SimpleTesting  public static void main(String[] args)   String filePath = "files/record.txt";  File file = new File(filePath);  String path = file.getPath();  System.out.println(path);  > > 

Define Relative Path for Parent Directory in Java

We can use the ../ prefix with the file path to locate a file in the parent directory. This is the relative path for accessing a file in the parent directory. See the example below.

import java.io.File; public class SimpleTesting  public static void main(String[] args)   String filePath = "../files/record.txt";  File file = new File(filePath);  String path = file.getPath();  System.out.println(path);  > > 

Define Relative Path in Current Directory in Java

If the file resource is located in the current directory, we can use the ./ prefix with the path to create a relative file path. See the example below.

import java.io.File; public class SimpleTesting  public static void main(String[] args)   String filePath = "./data-files/record.txt";  File file = new File(filePath);  String path = file.getPath();  System.out.println(path);  > > 

Define Relative Path Using the ../../ Prefix in Java

If the file is located in two levels upper in the directory structure, use the ../../ prefix with the file path. See the below example.

import java.io.File; public class SimpleTesting  public static void main(String[] args)   String filePath = "../../data-files/record.txt";  File file = new File(filePath);  String path = file.getPath();  System.out.println(path);  String absPath = file.getAbsolutePath();  System.out.println(absPath);  > > 

Related Article — Java Path

Related Article — Java IO

Источник

Читайте также:  Sun java 64 bit
Оцените статью