Java путь файла слэш

Paths.get() removes slash

send pies

posted 7 years ago

  • Report post to moderator
  • send pies

    posted 7 years ago

  • Report post to moderator
  • The slash character, «/» is an escape character in Java; when you want one to show up you have to put 2—you must escape the escape character.

    Out on HF and heard nobody, but didn’t call CQ? Nobody heard you either. 73 de N7GH

    Java Cowboy

    Scala

    send pies

    posted 7 years ago

    • 3
  • Report post to moderator
  • Les, I’m afraid that’s incorrect. The backslash \ is an escape character in Java string literals; the regular slash / is not and does not need to be escaped.

    Paths.get(. ) resolves a path on the file system. It does not expect an URL, but a filesystem path. So you get weird results if you give it an URL instead of a filesystem path.

    Note that there is a version of Paths.get that takes an URI instead of a string. But you need to explicitly give it an URI object:

    I doubt however how useful it is to call this with a http: URI. A Path is a path to something in a file system, so a file: URI would work, but you might not get anything that makes sense when you give it a http: URI. (You’ll most likely get an exception because there’s no filesystem provider for the «http» scheme).

    send pies

    posted 7 years ago

  • Report post to moderator
  • Jasper,
    Yes, you are absolutely right. I am afraid I have always had problems distinguishing the slash from the backslash. even when I say slash for some reason I am picturing a backslash in my mind.

    Jesper de Jong wrote: Les, I’m afraid that’s incorrect. The backslash \ is an escape character in Java string literals; the regular slash / is not and does not need to be escaped.

    Out on HF and heard nobody, but didn’t call CQ? Nobody heard you either. 73 de N7GH

    Читайте также:  Create directory using php

    send pies

    posted 7 years ago

  • Report post to moderator
  • String path = Paths.get(URI.create(«http://abc:4532/sample»)).toString(); gives java.nio.FileSystemNotFoundException. Provider «http» not installed

    Marshal

    send pies

    posted 7 years ago

  • Report post to moderator
  • Are you actually using http://abc:4532/sample? That appears to be a non‑existent URI, so you are going to get an Exception.

    If you have things on your own machine, I thought the URI started file:// but I may be mistaken.

    Saloon Keeper

    send pies

    posted 7 years ago

  • Report post to moderator
  • Campbell Ritchie wrote: Are you actually using http://abc:4532/sample? That appears to be a non‑existent URI, so you are going to get an Exception.

    If you have things on your own machine, I thought the URI started file:// but I may be mistaken.

    To access local files via a URI provider, the URL is «file:///dir1/dir2/file». The first 2 slashes are part of the URL coding convention (One of these days, I really should read up on why, but if nothing else, they indicate that optional hostname follows). The third slash indicates the root of the filesystem. Omit this and you have a relative-path URI, not an absolute-path URI. For URIs, you should always use «real» slashes, not backslashes. Backslashes will sometimes be honored (when properly escaped), but they’re awkward (need escapes) and not portable (only DOS/Windows uses them). A URI is a logical resource locator, not a literal OS filesystem path, so using forward slashes is a universal path notation. For example, on the old minicomputers I used to work with, a file path would be in the form «/dir1/dir2/file», but the URI would have been «file:///volume/dir1/dir2/file». Except that we didn’t have URIs back then.

    The secret of how to be miserable is to constantly expect things are going to happen the way that they are «supposed» to happen.

    Читайте также:  Установка whl python windows

    You can have faith, which carries the understanding that you may be disappointed. Then there’s being a willfully-blind idiot, which virtually guarantees it.

    Источник

    Как избежать слэшей в аргументе командной строки (путь к файлу) в Java?

    Обратите внимание, что я разрабатываю это с помощью NetBeans под Windows. Я также запускаю JDK 1.8.

    Программа использует несколько аргументов через командную строку. Один аргумент – путь к файлу. Пользователь может ввести -i C:\test . Как избежать косой черты? Кажется, что ничего не работает.

    public class Test < public static void main(String[] args) throws FileNotFoundException, ParseException < // Simulate command line execution String[] arguments = new String[] < "-i C:\test" >; // Create Options object Options options = new Options(); // Add options input directory path. options.addOption("i", "input", true, "Specify the input directory path"); // Create the parser CommandLineParser parser = new GnuParser(); // Parse the command line CommandLine cmd = parser.parse(options, arguments); String inputDirectory = cmd.getOptionValue("i"); String escaped; // Gives error of "invalid regular expression: Unexpected internal error escaped = inputDirectory.replaceAll("\\", "\\\\"); // This does not work File file = new File (escaped); Collection files = FileUtils.listFiles(file, null, false); // This works File file2 = new File ("C:\\test"); Collection files2 = FileUtils.listFiles(file2, null, false); > > 

    Я попробовал replaceAll, но, как говорится в коде, он не компилируется и возвращает недопустимую ошибку регулярного выражения.

    Я знаю, что лучше всего использовать File.separator, но я честно не знаю, как я могу применить его к аргументу командной строки. Возможно, пользователь может ввести относительный путь. Путь к файлу ссылки на пользователя также могут быть на любом диске.

    Как мне избежать обратных косых черт, чтобы я мог прокручивать каждый файл с помощью FileUtils?

    Читайте также:  Document

    Большое спасибо за любую помощь.

    escaped = inputDirectory.replaceAll("\\", "\\\\"); 
    escaped = inputDirectory.replaceAll(Pattern.quote("\\"), Matcher.quoteReplacement("\\\\")); 

    Поскольку вы подражаете аргументу в своей программе, учтите, что

    Фактически будет tab (т.е.\T) между C: и est

    но я честно не знаю, как я могу применить его к аргументу командной строки.

    Если ваша проблема заключается в том, как передавать аргументы командной строки, вы можете либо использовать команду java в командной строке Windows, как описано ниже.

    Или если вы хотите передать аргументы в netbeans по свойствам проекта → run, а затем добавить все параметры в поле аргументов, как показано ниже.

    Источник

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