Java 如何确定路径是否为本地文件

Java 如何确定路径是否为本地文件,java,android,Java,Android,给定一个作为字符串的位置,是否有可靠的方法来确定这是本地文件(如/mnt/sdcard/test.jpg)还是远程资源(如) 用Uri.parse将其转换为Uri似乎并没有给我任何指示文件所在位置的信息 我真的不想在字符串中查找// uri格式是 <protocol>://<server:port>/<path> 或者只是 /mnt 所以如果字符串以 \w+?:// 这不是file://那么这是url你也可以在类中进行检查 或上述类的任何其他成员函数建

给定一个作为字符串的位置,是否有可靠的方法来确定这是本地文件(如/mnt/sdcard/test.jpg)还是远程资源(如)

用Uri.parse将其转换为Uri似乎并没有给我任何指示文件所在位置的信息

我真的不想在字符串中查找//

uri格式是

<protocol>://<server:port>/<path>
或者只是

 /mnt
所以如果字符串以

\w+?://

这不是file://那么这是url

你也可以在类中进行检查

或上述类的任何其他成员函数建议在其前面加上验证

URLUtil.isValidUrl(file)
基于,这正是我使用的Java代码:

String path = "http://example.com/something.pdf";
if (path.matches("(?!file\\b)\\w+?:\\/\\/.*")) {
    // Not a local file
}

我也遇到了同样的问题,并尝试使用Penkov Vladimir解决方案,但没有成功,因为Uri的“内容”模式也不是远程资源

我使用了下面的代码,效果非常好

List<Uri> urls = new ArrayList<>();
List<Uri> locals = new ArrayList<>();
for (Uri uri : uris) {
    if (uri.getScheme() != null && (uri.getScheme().equals("content") || uri.getScheme().equals("file"))) {
        locals.add(uri);
    } else {
        urls.add(uri);
    }
}
List url=new ArrayList();
List locals=new ArrayList();
for(Uri:Uri){
if(uri.getScheme()!=null&(uri.getScheme().equals(“内容”)| | uri.getScheme().equals(“文件”)){
locals.add(uri);
}否则{
添加(uri);
}
}

要检查它是否是本地文件,只需执行以下操作:

public static boolean isLocalFile(String path) {
        return new File(path).exists();
}
要检查它是否是url,Cameron Ketcham的答案是最好的。

要避免硬编码:

import java.io.File;
import java.net.MalformedURLException;
import java.net.URI;
import java.net.URL;
import java.nio.file.Path;
import java.nio.file.Paths;

public class Test {

  public static void main( String args[] ) throws Exception {
    final String[] inputs = {
      "/tmp/file.txt",
      "http://www.stackoverflow.com",
      "file:///~/calendar",
      "mailto:java-net@java.sun.com",
      "urn:isbn:096139210x",
      "gopher://host.com:70/path",
      "wais://host.com:210/path",
      "news:newsgroup",
      "nntp://host.com:119/newsgroup",
      "finger://user@host.com/",
      "ftp://user:password@host.com:2121/",
      "telnet://user:password@host.com",
      "//localhost/index.html"
    };


    for( final String input : inputs ) {
      System.out.println( "---------------------------------------------" );

      final String protocol = getProtocol( input );
      System.out.println( "protocol: " + protocol );

      if( "file".equalsIgnoreCase( protocol ) ) {
        System.out.println( "file    : " + input );
      }
      else {
        System.out.println( "not file: " + input );
      }
    }
  }

  /**
   * Returns the protocol for a given URI or filename.
   *
   * @param source Determine the protocol for this URI or filename.
   *
   * @return The protocol for the given source.
   */
  private static String getProtocol( final String source ) {
    assert source != null;

    String protocol = null;

    try {
      final URI uri = new URI( source );

      if( uri.isAbsolute() ) {
        protocol = uri.getScheme();
      }
      else {
        final URL url = new URL( source );
        protocol = url.getProtocol();
      }
    } catch( final Exception e ) {
      // Could be HTTP, HTTPS?
      if( source.startsWith( "//" ) ) {
        throw new IllegalArgumentException( "Relative context: " + source );
      }
      else {
        final File file = new File( source );
        protocol = getProtocol( file );
      }
    }

    return protocol;
  }

  /**
   * Returns the protocol for a given file.
   *
   * @param file Determine the protocol for this file.
   *
   * @return The protocol for the given file.
   */
  private static String getProtocol( final File file ) {
    String result;

    try {
      result = file.toURI().toURL().getProtocol();
    } catch( Exception e ) {
      result = "unknown";
    }

    return result;
  }
}
输出:

---------------------------------------------
protocol: file
file    : /tmp/file.txt
---------------------------------------------
protocol: http
not file: http://www.stackoverflow.com
---------------------------------------------
protocol: file
file    : file:///~/calendar
---------------------------------------------
protocol: mailto
not file: mailto:java-net@java.sun.com
---------------------------------------------
protocol: urn
not file: urn:isbn:096139210x
---------------------------------------------
protocol: gopher
not file: gopher://host.com:70/path
---------------------------------------------
protocol: wais
not file: wais://host.com:210/path
---------------------------------------------
protocol: news
not file: news:newsgroup
---------------------------------------------
protocol: nntp
not file: nntp://host.com:119/newsgroup
---------------------------------------------
protocol: finger
not file: finger://user@host.com/
---------------------------------------------
protocol: ftp
not file: ftp://user:password@host.com:2121/
---------------------------------------------
protocol: telnet
not file: telnet://user:password@host.com
---------------------------------------------
Exception in thread "main" java.lang.IllegalArgumentException: Relative context: //localhost/index.html
    at Test.getProtocol(Test.java:67)
    at Test.main(Test.java:30)

检查www,http或.com?String str=“local file”或“remote file”,然后如果((str.indexOf(“http”)| | str.indexOf(“www”)==-1{//local file}或者{//remote file},我认为这可能会有所帮助you@Gens&@立管-还必须包括一些其他组合。如果协议既不是http(例如https),也不是子域是www,那么这将不起作用。虽然我希望有一个核心方法能为我做到这一点,但我想我可能不得不选择一个正则表达式解决方案,比如@Penkov Vladimir建议的下面这应该被接受,这是最简单、最优雅的方法!但是
URLUtil.isFileUrl(“/mnt/sdcard/somefile.txt”)
返回
false
。不适用于此路径/storage/emulated/0/Botad News/Images/welcome to Botad,名称足够了。pngstatic final String FILE_BASE=“FILE://”
code
public静态布尔值isFileUrl(stringurl){return(null!=url)&&&(url.startsWith(FILE_BASE)&&!url.startsWith(ASSET_BASE)&&&!url.startsWith(PROXY_BASE));}`这个答案已经过时了,因为我们有了新的FileProviderAPI,并且本地文件可能存在于内容URI中
isFileUrl()
不会检查url是否以
内容开始:
/tmp/file.txt
文件:///~/calendar
作为文件。这是因为上面的正则表达式与远程文件匹配。也许我们需要另一个正则表达式来确定“非远程文件”到底是不是文件(参见urn:isbn:096139210x)。但是,如果您现在已经在处理文件位置,那么这个正则表达式应该执行有关android的技巧?
import java.io.File;
import java.net.MalformedURLException;
import java.net.URI;
import java.net.URL;
import java.nio.file.Path;
import java.nio.file.Paths;

public class Test {

  public static void main( String args[] ) throws Exception {
    final String[] inputs = {
      "/tmp/file.txt",
      "http://www.stackoverflow.com",
      "file:///~/calendar",
      "mailto:java-net@java.sun.com",
      "urn:isbn:096139210x",
      "gopher://host.com:70/path",
      "wais://host.com:210/path",
      "news:newsgroup",
      "nntp://host.com:119/newsgroup",
      "finger://user@host.com/",
      "ftp://user:password@host.com:2121/",
      "telnet://user:password@host.com",
      "//localhost/index.html"
    };


    for( final String input : inputs ) {
      System.out.println( "---------------------------------------------" );

      final String protocol = getProtocol( input );
      System.out.println( "protocol: " + protocol );

      if( "file".equalsIgnoreCase( protocol ) ) {
        System.out.println( "file    : " + input );
      }
      else {
        System.out.println( "not file: " + input );
      }
    }
  }

  /**
   * Returns the protocol for a given URI or filename.
   *
   * @param source Determine the protocol for this URI or filename.
   *
   * @return The protocol for the given source.
   */
  private static String getProtocol( final String source ) {
    assert source != null;

    String protocol = null;

    try {
      final URI uri = new URI( source );

      if( uri.isAbsolute() ) {
        protocol = uri.getScheme();
      }
      else {
        final URL url = new URL( source );
        protocol = url.getProtocol();
      }
    } catch( final Exception e ) {
      // Could be HTTP, HTTPS?
      if( source.startsWith( "//" ) ) {
        throw new IllegalArgumentException( "Relative context: " + source );
      }
      else {
        final File file = new File( source );
        protocol = getProtocol( file );
      }
    }

    return protocol;
  }

  /**
   * Returns the protocol for a given file.
   *
   * @param file Determine the protocol for this file.
   *
   * @return The protocol for the given file.
   */
  private static String getProtocol( final File file ) {
    String result;

    try {
      result = file.toURI().toURL().getProtocol();
    } catch( Exception e ) {
      result = "unknown";
    }

    return result;
  }
}
---------------------------------------------
protocol: file
file    : /tmp/file.txt
---------------------------------------------
protocol: http
not file: http://www.stackoverflow.com
---------------------------------------------
protocol: file
file    : file:///~/calendar
---------------------------------------------
protocol: mailto
not file: mailto:java-net@java.sun.com
---------------------------------------------
protocol: urn
not file: urn:isbn:096139210x
---------------------------------------------
protocol: gopher
not file: gopher://host.com:70/path
---------------------------------------------
protocol: wais
not file: wais://host.com:210/path
---------------------------------------------
protocol: news
not file: news:newsgroup
---------------------------------------------
protocol: nntp
not file: nntp://host.com:119/newsgroup
---------------------------------------------
protocol: finger
not file: finger://user@host.com/
---------------------------------------------
protocol: ftp
not file: ftp://user:password@host.com:2121/
---------------------------------------------
protocol: telnet
not file: telnet://user:password@host.com
---------------------------------------------
Exception in thread "main" java.lang.IllegalArgumentException: Relative context: //localhost/index.html
    at Test.getProtocol(Test.java:67)
    at Test.main(Test.java:30)