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;
}
}
Related
I'm still learning Java and I need some help understanding why this code is wrong:
BufferedReader infile = new BufferedReader(new FileReader(file));
String regel = infile.readLine();
while (regel != null) {
// Do something with regel.
regel = infile.readLine();
}
infile.close();
I really don't see the problem but Eclipse keeps telling there is a resource leak and that infile isn't closed.
(one more detail, this code stands in a try block but I left it away to keep it simple)
Eclipse is complaining because the reference may not be closed (for example, in an Exception); this is where you would use a finally block - perhaps like so
BufferedReader infile = null;
try {
infile = new BufferedReader(new FileReader(file));
String regel = infile.readLine();
while (regel != null) {
// Do something with regel.
regel = infile.readLine();
}
} catch (Exception e) {
e.printStackTrace(); // Log the exception.
} finally {
if (infile != null) {
infile.close(); // close the resource.
}
}
You should have a try/catch block.
Also you should use the following instead:
while ((line = reader.readLine()) != null) {
//do something with line;
}
I think Elliott Frisch is correct and pointed out the main reason the only thing I would add is You should close the stream (in a finally block) because to ensure that any output buffers are flushed in the case that output was otherwise successful. If the flush fails, the code should exit via an exception. Here is another example similar to what you are trying to solve and make sure you look at (Guideline 1-2: Release resources in all cases) http://www.oracle.com/technetwork/java/seccodeguide-139067.html
final OutputStream rawOut = new FileOutputStream(file);
try {
final BufferedOutputStream out =
new BufferedOutputStream(rawOut);
use(out);
out.flush();
} finally {
rawOut.close();
}
i am using java ant to deploy my application . I have a file app.php . I want to write some text in app.php while deploying in a specific location inside that file . This is my app.php :
'providers' => array(
'Illuminate\Validation\ValidationServiceProvider',
'Illuminate\View\ViewServiceProvider',
'Illuminate\Workbench\WorkbenchServiceProvider',
),
I want to add a line at the end of this line :
'Illuminate\Workbench\WorkbenchServiceProvider',
Please tell me how to do this .
Thanks.
you must use subString method like this:
at first store your file in a String so after that you could do this:
String s="your file";
String firstPart=s.substring(0,s.lastIndexOf(")")+1);
String lastPart=s.substring(s.lastIndexOf(")")+1);
firstPart=firstPart+"\n"+"'Illuminate\\Workbench\\WorkbenchServiceProvider',";
s=firstPart+lastPart;
How to read from file ?
Use BufferedReader to wrap a FileReader
BufferedReader br = null;
StringBuilder sb=new StringBuilder();
try {
String line;
br = new BufferedReader(new FileReader("C:\\testing.txt"));
while ((line= br.readLine()) != null) {
sb.append(line+"\n");
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (br != null)br.close();
} catch (IOException ex) {
ex.printStackTrace();
}
}
String str=sb.toString();
See the Replace or Filter ant tasks.
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?
Can someone help me in the below scenario,
I need to call a perl script from my java code. The perl script is an interactive code, which gets the input from the user during its execution and continues further to end. So, the example I have used is, the perl script when executed asks for the age by printing in the console "How old are you?", when the user enter some value say '26'. Then it prints "WOW! You are 26 years old!".
When I tried calling this script from my java code, the process waits till I give the value as 26 in the outputstream, while in the inputstream there is no value. Then finally when again I read the inputstream, i get the entire output of the script together. So, here can't I make it interactive?
I have went through many forums and blogs, but couldn't locate any, which exactly target my requirement.
Here is the java code
import java.io.*;
public class InvokePerlScript {
/**
* #param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
Process process;
try
{
process = Runtime.getRuntime().exec("cmd /c perl D:\\sudarsan\\eclips~1\\FirstProject\\Command.pl");
try {
BufferedReader in = new BufferedReader(new InputStreamReader(process.getInputStream()));
String line = null;
while ((line = in.readLine()) != null) {
System.out.println(line);
}
} catch (IOException e) {
e.printStackTrace();
}
try {
BufferedWriter out = new BufferedWriter(new OutputStreamWriter(process.getOutputStream()));
out.write("23");
out.flush();
out.close();
} catch (IOException e) {
e.printStackTrace();
}
process.waitFor();
if(process.exitValue() == 0)
{
System.out.println("Command Successful");
try {
BufferedReader in = new BufferedReader(new InputStreamReader(process.getInputStream()));
String line = null;
while ((line = in.readLine()) != null) {
System.out.println(line);
}
} catch (IOException e) {
e.printStackTrace();
}
}
else
{
System.out.println("Command Failure");
try {
BufferedReader in = new BufferedReader(new InputStreamReader(process.getErrorStream()));
String line = null;
while ((line = in.readLine()) != null) {
System.out.println(line);
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
catch(Exception e)
{
System.out.println("Exception: "+ e.toString());
}
}
}
Perl code is as below
$| = 1;
print "How old are you? \n";
$age = <>;
print "WOW! You are $age years old!";
Thanks in advance,
Sudarsan
Are you calling flush() on the OutputStream in Java after writing the values? If you don't, there's a good chance they'll just be held in the stream's buffer within the Java process, and so never make it to Perl (with the result that both processes end up waiting for the other's IO.)
(Depending on the implementation of the stream this may or may not be necessary, but it certainly wouldn't hurt - and I've been bitten by this in the past. Usually one doesn't need to be as careful, since flushing happens implicitly when close() is called, but here you can't close the stream after you've finished writing.)
It looks like you're trying to read a full line in this code:
BufferedReader in = new BufferedReader(new InputStreamReader(process.getInputStream()));
String line = null;
while ((line = in.readLine()) != null) {
...
However, in your perl code, you are not printing an endline character, so readLine never returns (as per the documentation).
I just wanted to know if there is any restriction on the number of lines readLine method can read from a file in java.Any help will be grately appreciated.This is what I am talking about:
FileReader fr1=new FileReader("/homes/output_train_2000.txt");
BufferedReader br1=new BufferedReader(fr1);
while((line1=br1.readLine())!=null){ }
Thanks.
When buffered reader is used, the entire file is never read into memory, so it should be able to handle files of any size that your operating system supports for.
It can read any number of lines .
Are you trying to restrict the number of lines read? If so then you can easily add some code to do that:
FileReader fr1=new FileReader("/homes/output_train_2000.txt");
BufferedReader br1=new BufferedReader(fr1);
int numLinesRead = 0;
int maxLines = 1000;
while((numLinesRead < maxLines) && (line1=br1.readLine())!=null){
numLinesRead++;
// other stuff
}
No restriction that I know of. Here's a better way of doing it:
BufferedReader reader = null;
try {
reader = new BufferedReader( new FileReader( "/homes/output_train_2000.txt") );
String line = null;
do {
line = reader.readLine();
if( line != null ) {
// Do something
}
} while( line != null );
} catch (Exception e) {
e.printStackTrace();
} finally {
if( reader != null )
try {
reader.close();
} catch (IOException e) {
}