Created
November 6, 2013 14:19
-
-
Save caner/c43b638796343c68f98f to your computer and use it in GitHub Desktop.
try-with-resources sample
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/*geleneksel try-catch-finally bloku: | |
* genellikle finally blokunda kullanılan stream, reader vs. kapatılır | |
*/ | |
static String readFirstLineFromFileWithFinallyBlock(String path) | |
throws IOException { | |
BufferedReader br = new BufferedReader(new FileReader(path)); | |
try { | |
return br.readLine(); | |
} finally { | |
//bu örnekteki kaynağı kapatmasanız belki sorun | |
//çıkarmayacaktır fakat bu durum yine de bir bellek sızıntısına | |
//memory-leak sebep verir. bu pek sevilmez. | |
//örneğin android'te böyle arızalar çıkaracak olursanız | |
//uygulamanız özellikle SQLite vs. kullanırken Cursor gibi sınıflarda | |
//sistem belleğine iyi davranmıyor olacaktır. | |
if (br != null) br.close(); | |
} | |
} | |
//src: http://docs.oracle.com/javase/tutorial/essential/exceptions/tryResourceClose.html |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/*yeni try-with-resources yapısı | |
* elbette burada da finally bloku kullanımı mümkün. illâ | |
* kaynakları kapatmak için finally bloku kullanmıyoruz sonuçta. | |
*/ | |
static String readFirstLineFromFile(String path) throws IOException { | |
try (BufferedReader br = new BufferedReader(new FileReader(path))) { | |
return br.readLine(); | |
//romantik bir kısa hâl. BufferedReader'a benzer çok stream | |
//ile alakalı sınıf var Android'te. kaynağı oluştur ve kullan, | |
//yok edilmesine karışma. güzel duruyor. | |
} | |
} | |
//src: http://docs.oracle.com/javase/tutorial/essential/exceptions/tryResourceClose.html |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment