Path java не работает

Writing to a file in Java: Cannot find the path specified

I am having enormous difficulty writing to a simple text file in Java. Every search I’ve done for the IO exception I’m getting is turning up plenty of suggestions, but none of them apply to this situation. Here is my project structure:

MyEclipseProject/ src/ com.myprogram.utils MyProgram bin/ 
package com.myprogram.utils; import java.io.FileWriter; public class MyProgram < public static void main(String[] args) < FileWriter oWriter = new FileWriter(new File("logs/system.log")); oWriter.write("This never gets logged because JRE can't find the file"); >> 

The exception message I’m getting states: logs\system.log (The system cannot find the path specified). The first time I tried, I did so without having first created the logs/ directory and its subsequent log file. My understanding was that, if Java couldn’t find the file, it would create it for you. I have now placed a logs folder — with a blank system.log file — inside: (1) my project root ( MyEclipseProject ), (2) the src/ folder, (3) the src/com.myprogram.utils package, and (4) the bin folder, and I am getting the same exact error. I’m wondering: could I have an OS/persmissions thing going on? Could my app be trying to create the folder and log file but be getting denied permission to do so by Windows 7? If so, what do I do. If not, where in tarnation do I place logs/system.log . Thank you for any clarity to this!

Читайте также:  Including wp blog header php

Источник

Ошибка чтения пути paths.get() java

получаю вот такую ошибку при использовании paths. Ссылку получаю из БД postgre. Не могу понять, что не так с ссылкой.

java.nio.file.InvalidPathException: Illegal char at index 4: http://localhost:8080/download/2QkQNYMM84w.jpg 
 @PostMapping("/update-picture") @ResponseStatus public FileResponse updatePicture(@RequestParam("file") MultipartFile multipartFile, HttpServletRequest request)

1 ответ 1

Судя по всему, трюк с Paths.get для получения имени файла из адреса работает не везде. Под Windows, класс, отвечающий за файловую систему, sun.nio.fs.WindowsPathParser проверяет, что в пути указан максимум один однобуквенный диск в начале строки и что в остальной строке нет двоеточия.

Не рекомендую усугублять ситуацию и пытаться подстроить веб-адрес под требования Paths.get . Лучше выберите другой способ определения имени файла. Множество таких способов можно найти в таком же вопросе на английском: Get file name from URL.

Самый популярный ответ предлагает подключить Apache Commons (commons-io):

String filename = FilenameUtils.getName(user.getUrl_picture().trim()); storageService.delete(filename); 

Вроде бы это работает, хотя FilenameUtils тоже предназначен для файловой системы. Протестируйте повнимательнее случай адресов с GET параметрами.

Дополнение: «Хорошего» класса, предназначенного именно для URL, решающего эту задачу, я так сразу не нашел. Если FilenameUtils по каким-то причинам не сработает, то можно пойти на крайние меры, а именно на регулярное выражение:

    *
  • [^/\\&\?]+ — имя файла (любой набор символов кроме /, \, & и ?) *
  • .\\w — расширение (от одной до пяти букв) *
  • (?=([\?&].*$|$)) — проверка что после файла либо конец строки, либо * GET-параметры. *

Источник

Java NIO file path issue

I wonder why I get the leading character a ‘/’, instead of ‘\’ like in the question. I’m using Windows 10, Java 8, Spring 3.2.14.RELEASE.

The error in our case was from: ClassLoader.getSystemResource(«something»).getPath() — on windows it was dropping file: from file:/C:/mypath

8 Answers 8

You need to convert the found resource to URI. It works on all platforms and protects you from possible errors with paths. You must not worry about how full path looks like, whether it starts with ‘\’ or other symbols. If you think about such details — you do something wrong.

ClassLoader classloader = Thread.currentThread().getContextClassLoader(); String platformIndependentPath = Paths.get(classloader.getResource(errorFile).toURI()).toString(); 

It’s better than the accepted answer because sometimes, it won’t be you who will type the path, but you will get it by using something like ClassLoader.getResource() in which case it will automatically add that backslash that he talked about in the accepted answer! +1

The path \C:\Sample\sample.txt must not have a leading \ . It should be just C:\Sample\sample.txt

wa~, get a absolute path, and developer must remove a «/» at head, Isn’t it a bug in WindowsOS or Path class ?

The same issue I get while executing in jenkins java.nio.file.InvalidPathException: Illegal char at index 0: «—tags at web.TestParallel.testParallel(TestParallel.java:23) Line 23: Results results = Runner.parallel(getClass(), 5, «target/surefire-reports»);

To make it work on both Windows and Linux\OS X consider doing this:

String osAppropriatePath = System.getProperty( "os.name" ).contains( "indow" ) ? filePath.substring(1) : filePath; 

If you want to worry about performance I’d store System.getProperty( «os.name» ).contains( «indow» ) as a constant like

private static final boolean IS_WINDOWS = System.getProperty( "os.name" ).contains( "indow" ); 
String osAppropriatePath = IS_WINDOWS ? filePath.substring(1) : filePath; 

To be sure to get the right path on Windows or Linux on any drive letter, you could do something like this:

That says: If the beginning of the string is a slash, then a character, then a colon and another slash, replace it with the character, the colon, and the slash (leaving the leading slash off).

If you’re on Linux, you shouldn’t end up with a colon in your path, and there won’t be a match. If you are on Windows, this should work for any drive letter.

In the OP the leading character is ‘\’, though I am get the ‘/’ character, like in your answer, any thoughts on why the difference?

Ah, good catch. No, I’m not sure why the difference. I personally saw the / . So, if someone is seeing `, they could modify the regular expression to catch the `.

Could grab the Environment path separator, or use «^[/\\/](.:/)» the character class would match either slash.

Another way to get rid of the leading separator is to create a new file and convert it to a string then:

new File(Platform.getInstallLocation().getURL().getFile()).toString() 

try to use like this C:\\Sample\\sample.txt

Note the double backslashes. Because the backslash is a Java String escape character, you must type two of them to represent a single, «real» backslash.

Java allows either type of slash to be used on any platform, and translates it appropriately. This means that you could type. C:/Sample/sample.txt

and it will find the same file on Windows. However, we still have the «root» of the path as a problem.

The easiest solution to deal with files on multiple platforms is to always use relative path names. A file name like Sample/sample.txt

Источник

Слетает Path для Java при перезапуске ПК на Windows 10

Java Path настроен и всё работает,но при перезапуске ПК слетает,пример: включаю ПК,и при попытке скомпилировать/запустить программу/узнать версию java или компилятора получается следующее: введите сюда описание изображения Лечиться это так: просто захожу в переменные среды и просто нажимаю ок,ничего не меняя,всё начинает работать: введите сюда описание изображения Попытка номер 2 и теперь всё работает: введите сюда описание изображения Теперь всё работает как надо,при перезагрузке ПК всё продолжает работать,но если выключить ПК и затем включить,то опять возникает та же проблема.Собственно проблема не критичная,просто надоело после каждого включения ПК в переменные среды заходить.Кто знает,в чём может быть проблема?Вот моя JAVA_HOME: введите сюда описание изображения И Path: введите сюда описание изображения

1 ответ 1

Снеси java и снова установи!Т.е. все включая и JDK, JRE.

указал путь без bin,теперь компилятор вообще работать перестал,вернул обратно bin,системный диск С,просто это ссд и я его чисто для системы использую,а на D создал каталог где jdk,jre,сорсы, документация,и там же сами программы,мне так просто удобнее когда всё в 1 папке

Так а какой у тебя диск системный C или D? надо в системный ставить! mkyong.com/java/how-to-set-java_home-on-windows-10 Почитай тут

Источник

Оцените статью