My code is reading an HTML page from the web and I want to write good code, so I would like to close the resources using try-with-resources or finally block.
With the following code it seems impossible to use either of them to close "in".
try {
URL url = new URL("myurl");
BufferedReader in = new BufferedReader(
new InputStreamReader(
url.openStream()));
String line = "";
while((line = in.readLine()) != null) {
System.out.println(line);
}
in.close();
}
catch (IOException e) {
throw new RuntimeException(e);
}
Would you be able to write the same code using try-with-resources or finally?
I don't see any particular difficulty with the following:
try (BufferedReader in = new BufferedReader(new InputStreamReader(
new URL("myurl").openStream()))) {
String line = "";
while ((line = in.readLine()) != null) {
System.out.println(line);
}
} catch (IOException e) {
throw new RuntimeException(e);
}
Is it not what you're looking for?
Related
what would be the equivalent of this code:
FileReader reader = null;
try
{
reader = new FileReader( file);
return reader.ready();
}
catch( IOException ex)
{
return false;
}
For SmbFile ? I tried that:
BufferedReader reader = null;
try
{
SmbFileInputStream fstream = new SmbFileInputStream( file);
reader = new BufferedReader( new InputStreamReader( fstream));
return reader.ready();
}
catch( IOException ex)
{
return false;
}
but then I always get "false" as result.
Based on the documentation looks that there's no guarantee that this flag assure it cannot be read, Note that returning false does not guarantee that the next read will block.
You can try this way to avoid null values,
String line;
while((line = br.readLine()) != null) {
System.out.println(line);
}
You can look at this post too, bufferedreader-not-stating-ready-when-it-should
Hope this helps
i want to get the entire content of url (i.e) till the end of that url..
but after getting few contents because of partial loading ..i cant able to get remaining contents...is there is any way to get whole content from url even after the partial loading ...
String url = "URL/"; // getting URL
try {
Document doc = Jsoup.connect(url).get();
FileWriter fw=null;
BufferedWriter bw=null;
fw=new FileWriter("D:\\url.txt");
bw=new BufferedWriter(fw);
String line = doc.text();
System.out.println(line);
bw.write(line);
} catch (IOException ex) {
Logger.getLogger(NewJFrame.class.getName())
.log(Level.SEVERE, null, ex);
}
Sorry for the late answer, dinner...
An answer can be found here: Read url to string in few lines of java code
Idk if it's your question is a duplicate question or not...
Anyways, the traditional way to do it would be like this:
URL website = new URL("example.com");
URLConnection connection = website.openConnection();
BufferedReader in = new BufferedReader(
new InputStreamReader(
connection.getInputStream()));
StringBuilder response = new StringBuilder();
String inputLine;
while ((inputLine = in.readLine()) != null)
response.append(inputLine);
in.close();
Hope I helped!
URL website;
try {
website = new URL("https://news.google.co.in/");
URLConnection connection = website.openConnection();
BufferedReader in = new BufferedReader(
new InputStreamReader(
connection.getInputStream()));
StringBuilder response = new StringBuilder();
String inputLine;
while ((inputLine = in.readLine()) != null)
response.append(inputLine);
in.close();
System.out.print(response.toString());
} catch (MalformedURLException ex) {
Logger.getLogger(NewJFrame.class.getName()).log(Level.SEVERE, null, ex);
} catch (IOException ex) {
Logger.getLogger(NewJFrame.class.getName()).log(Level.SEVERE, null, ex);
}
and getting an html output
What i want is to reduce exceptions to be thrown from a method.
As you can see i have an inner try catch in the outer catch block to avoid the exception be thrown.
Is this the normal way to do this or are there better (more elegant) ways?
Or is this approach completely false and i should just throw the exception?
public static String readText(String filename) {
String text = "";
BufferedReader br = null;
try {
br = new BufferedReader(new FileReader(filename));
String line = null;
while( (line = br.readLine()) != null ){
text += line;
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if(br != null)
try {
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return text;
}
Personally I'd go for a more modern approach with either Files.readAllLines(); or Files.lines();.
Then all you need to handle is an IOException and the resources are cleaned up for you automatically.
There are several ways to be more concise in what you want to do:
Use a Java 7 feature to catch multiple exceptions in one catch:
try {...} catch(FileNotFoundException | IOException e) {...}
Use a Java 7 feature called try-with-resources so you can ommit the finally:
try (BufferedReader br =
new BufferedReader(new FileReader(filename))) {
}
In regards to throwing the exceptions or not is a design choice:
Do I want to signal errors to the upper layer?
Can I handle the error on the upper level?
If you are using Java 7 or later you can use try with resource.
try (BufferedReader br =
new BufferedReader(new FileReader(path))) {
String line = null;
while( (line = br.readLine()) != null ){
text += line;
}
}
I've been trying to read a file for the last few days and have tried following other answers but have not succeeded. This is the code I currently have to import the text file:
public ArrayList<String> crteDict() {
try {
BufferedReader br = new BufferedReader
(new FileReader("/program/res/raw/levels.txt"));
String line;
while ((line = br.readLine()) != null) {
String[] linewrds = line.split(" ");
words.add(linewrds[0].toLowerCase());
// process the line.
}
br.close();
}
catch (FileNotFoundException fe){
fe.printStackTrace();
It is meant to read the text file and just create a long Array of words. It keeps ending up in the FileNotFoundException.
Please let me know any answers.
Thanks!
IF your file is stored in the res/raw folder of the android project, you can read it as follows, this code must be inside an Activity class, as this.getResources() refers to Context.getResources():
// The InputStream opens the resourceId and sends it to the buffer
InputStream is = this.getResources().openRawResource(R.raw.levels);
BufferedReader br = new BufferedReader(new InputStreamReader(is));
String readLine = null;
try {
// While the BufferedReader readLine is not null
while ((readLine = br.readLine()) != null) {
Log.d("TEXT", readLine);
}
// Close the InputStream and BufferedReader
is.close();
br.close();
} catch (IOException e) {
e.printStackTrace();
}
This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
How to create a Java String from the contents of a file
Is it possible to process a multi-lined text file and return its contents as a string?
If this is possible, please show me how.
If you need more information, I'm playing around with I/O. I want to open a text file, process its contents, return that as a String and set the contents of a textarea to that string.
Kind of like a text editor.
Use apache-commons FileUtils's readFileToString
Check the java tutorial here -
http://download.oracle.com/javase/tutorial/essential/io/file.html
Path file = ...;
InputStream in = null;
StringBuffer cBuf = new StringBuffer();
try {
in = file.newInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
String line = null;
while ((line = reader.readLine()) != null) {
System.out.println(line);
cBuf.append("\n");
cBuf.append(line);
}
} catch (IOException x) {
System.err.println(x);
} finally {
if (in != null) in.close();
}
// cBuf.toString() will contain the entire file contents
return cBuf.toString();
Something along the lines of
String result = "";
try {
fis = new FileInputStream(file);
bis = new BufferedInputStream(fis);
dis = new DataInputStream(bis);
while (dis.available() != 0) {
// Here's where you get the lines from your file
result += dis.readLine() + "\n";
}
fis.close();
bis.close();
dis.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return result;
String data = "";
try {
BufferedReader in = new BufferedReader(new FileReader(new File("some_file.txt")));
StringBuilder string = new StringBuilder();
for (String line = ""; line = in.readLine(); line != null)
string.append(line).append("\n");
in.close();
data = line.toString();
}
catch (IOException ioe) {
System.err.println("Oops: " + ioe.getMessage());
}
Just remember to import java.io.* first.
This will replace all newlines in the file with \n, because I don't think there is any way to get the separator used in the file.