【问题标题】:Writing to a resource in Java? [duplicate]用 Java 写入资源? [复制]
【发布时间】:2013-07-04 16:07:51
【问题描述】:

我正在尝试使用 Class.getResource() 方法将数据保存到我计算机上的文件中。问题是它返回一个 URL。我找不到使用 url 写入文件的方法。这是我到目前为止的代码:

url = getClass().getResource("save.txt");
URLConnection urlconn = url.openConnection();
OutputStream os = urlconn.getOutputStream();
OutputStreamWriter isr = new OutputStreamWriter(os);
buffer = new BufferedWriter(isr);

当我运行这个时,我得到一个 java.net.UnknownServiceException:协议不支持输出 错误。我不知道该怎么办。

【问题讨论】:

  • 您能更具体地说明您要做什么吗?
  • 如果你只想写入输出流,你必须设置 os.setDoOutput(true) 我认为。
  • 更好地解释自己

标签: java resources


【解决方案1】:

你不能写这样的资源。它是只读的。

另一方面,您可以找出资源文件的路径。 其中一种方法可能是:

找出资源的路径

public static File findClassOriginFile( Class cls ){
    // Try to find the class file.
    try {
        final URL url = cls.getClassLoader().getResource( cls.getName().replace('.', '/') + ".class");
        final File file = new File( url.getFile() ); // toString()
        if( file.exists() )
            return file;
    }
    catch( Exception ex ) { }

    // Method 2
    try {
        URL url = cls.getProtectionDomain().getCodeSource().getLocation();
        final File file = new File( url.getFile() ); // toString()
        if( file.exists() )
            return file;
    }
    catch( Exception ex ) { }

    return null;
}

上面的方法为Class找到一个文件,但也可以很容易地更改为资源。

我建议使用默认资源,将其从类路径复制到某个工作目录并保存在那里。

将资源复制到目录

public static void copyResourceToDir( Class cls, String name, File dir ) throws IOException {
    String packageDir = cls.getPackage().getName().replace( '.', '/' );
    String path = "/" + packageDir + "/" + name;
    InputStream is = GroovyClassLoader.class.getResourceAsStream( path );
    if( is == null ) {
        throw new IllegalArgumentException( "Resource not found: " + packageDir );
    }
    FileUtils.copyInputStreamToFile( is, new File( dir, name ) );
}

【讨论】:

  • @AndrewThompson,你错了。对于getResourceAsStream()/ 就可以了。
  • 哦,对了。我的错。
猜你喜欢
  • 1970-01-01
  • 2013-04-04
  • 1970-01-01
  • 2014-03-05
  • 1970-01-01
  • 2013-07-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多