在Scala应用程序中,我尝试使用java nio try-with-resource构造从文件中读取行.
Scala版本2.11.8
Java版本1.8
try(Stream<String> stream = Files.lines(Paths.get("somefile.txt"))){
stream.forEach(System.out::println); // will do business process here
}catch (IOException e) {
e.printStackTrace(); // will handle failure case here
}
Run Code Online (Sandbox Code Playgroud)
但是编译器会抛出错误,例如
找不到:值流
◾尝试没有捕获或者最终等同于将其主体放入块中; 没有例外处理.
不确定是什么问题.我是使用Java NIO的新手,所以非常感谢任何帮助.
我有以下代码:
public class Main {
public static void main(String[] args) throws SQLException {
try (
Connection conn = DBUtil.getConnection(DBType.HSQLDB);
Statement stmt = conn.createStatement(
ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);
ResultSet rs = stmt.executeQuery("SELECT * FROM tours");
) {
DBUtil.getConnection();
} catch (SQLException e) {
DBUtil.processException(e);
}
}
}
Run Code Online (Sandbox Code Playgroud)
我使用此代码从数据库中获取数据.我的问题是我不允许使用Java 1.7编译器并且必须使用1.6.如何将try-with-resources-code转换为与1.6编译器一起使用?在这个特殊的尝试块中究竟发生了什么?
我在Kotlin中表达Java的try-with-resources构造时遇到了一些麻烦.在我的理解中,作为实例的每个表达式都AutoClosable应该提供use扩展函数.
这是一个完整的例子:
import java.io.BufferedReader;
import java.io.FileReader;
import org.openrdf.query.TupleQuery;
import org.openrdf.query.TupleQueryResult;
public class Test {
static String foo(String path) throws Throwable {
try (BufferedReader r =
new BufferedReader(new FileReader(path))) {
return "";
}
}
static String bar(TupleQuery query) throws Throwable {
try (TupleQueryResult r = query.evaluate()) {
return "";
}
}
}
Run Code Online (Sandbox Code Playgroud)
Java-to-Kotlin转换器创建此输出:
import java.io.BufferedReader
import java.io.FileReader
import org.openrdf.query.TupleQuery
import org.openrdf.query.TupleQueryResult
object Test {
@Throws(Throwable::class)
internal fun foo(path: String): String {
BufferedReader(FileReader(path)).use { r -> …Run Code Online (Sandbox Code Playgroud) 所以我正在研究java 7的一些新功能,包括try-with-resources位.
我理解它是如何工作的以及一切,我只是注意到用于指定资源的语法有点奇怪.
try
(InputStream fis = new FileInputStream(source);
OutputStream fos = new FileOutputStream(target))
{
// stuff
}
}
catch (Exception e) {
// stuff
}
Run Code Online (Sandbox Code Playgroud)
具体来说就是资源的定义:
try (InputStream fis = new FileInputStream(source);
OutputStream fos = new FileOutputStream(target))
Run Code Online (Sandbox Code Playgroud)
在Java中,括号内的分隔语句是否有效,是否还有其他地方?
我能想到的另一个时间是for循环
for ( ; ; )
Run Code Online (Sandbox Code Playgroud)
但这并不完全相同,因为必须有2 ;秒,并且语句用,as中分隔
for (int i = 1, j = 100; i <= 100, j > 0; i = i-1, j = j-1)
Run Code Online (Sandbox Code Playgroud)
所以我的问题是,这种语法来自哪里?是否有理由将语句;分隔而不是,分隔?是否有另一种类似的语言;在() …
我期望能发现XMLStreamReader是AutoCloseable在Java 7中.然而,事实并非如此.是否存在技术原因导致StAX读取器/写入器接口未被(或不应该)改进以实现AutoCloseable?他们已经有了密切的方法,其意图与密切方法没有区别AutoCloseable.
事实证明,几乎没有人正确地关闭Java中的资源.程序员要么不使用try-finally块可言,或只是把resource.close()在finally,这也是不正确的(因为Throwable从close()可影子Throwable从try块).有时他们把类似的东西IOUtils.closeQuietly()只是正确的InputStream,但不是OutputStream.try-with-resources解决了所有这些问题,但仍有大量的项目用Java 6编写.
try-with-resources在Java 6中模拟的最佳方法是什么?现在我使用的是Guava Closer,它比什么都好,但仍然比它更糟糕try-with-resources.此外,还有一种称为贷款模式的模式,但Java中缺少lambdas使得这种模式非常麻烦.有没有更好的办法?
我碰巧意识到,情况确实如此.请参阅以下示例:
public class AutoClosableTest {
public static void main(String[] args) throws Exception {
try (MyClosable instance = new MyClosable()) {
if (true) {
System.out.println( "try" );
throw new Exception("Foo");
}
} catch( Exception e ) {
System.out.println( "Catched" );
} finally {
System.out.println( "Finally" );
}
}
public static class MyClosable implements AutoCloseable {
@Override
public void close() throws Exception {
System.out.println( "Closed." );
}
}
}
Run Code Online (Sandbox Code Playgroud)
它打印:
尝试
关闭.
抓住了
最后
try-with-resources旨在避免使用null检查的杂乱的finally段,并避免泄漏的资源.为什么资源在捕获部分之前关闭?它背后的原因/想法/限制是什么?
这是Main.java:
package foo.sandbox.db;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
public class Main {
public static void main(String[] args) {
final String SQL = "select * from NVPAIR where name=?";
try (
Connection connection = DatabaseManager.getConnection();
PreparedStatement stmt = connection.prepareStatement(SQL);
DatabaseManager.PreparedStatementSetter<PreparedStatement> ignored = new DatabaseManager.PreparedStatementSetter<PreparedStatement>(stmt) {
@Override
public void init(PreparedStatement ps) throws SQLException {
ps.setString(1, "foo");
}
};
ResultSet rs = stmt.executeQuery()
) {
while (rs.next()) {
System.out.println(rs.getString("name") + "=" + rs.getString("value"));
}
} catch (Exception e) …Run Code Online (Sandbox Code Playgroud) 我想就使用托管资源的最佳设计模式绘制一些意见,其中涉及两个不同的资源,但您需要以与获取它们相反的顺序发布它们.
首先,让我设置场景.我们正在使用两种类型的对象文档和文档集合.文档集合字面上包含对文档的引用和每个文档的一些元数据.
最初我们有一个对称的图案流动如下:
并在代码中表示如下:
Collection col = null;
try {
col = getCollection("col1 name", LockMode.WRITE_LOCK);
// Here we do any operations that only require the Collection
Document doc = null;
try {
doc = col.getDocument("doc1 name", LockMode.WRITE_LOCK);
// Here we do some operations on the document (of the Collection)
} finally {
if (doc != null) {
doc.close();
}
}
} finally {
if (col != null) {
col.close();
}
}
Run Code Online (Sandbox Code Playgroud)
既然我们已经拥有try-with-resourcesJava …
我在Java 的try-with-resources文档中找到了这个例子:
static String readFirstLineFromFile(String path) throws IOException {
try (BufferedReader br = new BufferedReader(new FileReader(path))) {
return br.readLine();
}
}
Run Code Online (Sandbox Code Playgroud)
如果构造函数BufferedReader抛出异常,则FileReader不会释放由其持有的资源.所以这不是一个不好的做法,而不是:
static String readFirstLineFromFile(String path) throws IOException {
try (FileReader fr = new FileReader(path);
BufferedReader br = new BufferedReader(fr)) {
return br.readLine();
}
}
Run Code Online (Sandbox Code Playgroud)