How can I read line from text? Look at my code:
public static String getTemplateFromFile() {
String name = null;
try {
BufferedReader reader = new BufferedReader(new
FileReader(
"http://localhost:8080/blog/resources/cache/templateName.txt"));
name = reader.readLine();
//name="TEST";
//NULL anyway
reader.close();
}
catch (Exception e) {
}
return name;
}
Also I have got secnod version, but my server freeze.
public static String getTemplateFromFile() {
String name = null;
/*
try {
URL url = new URL("http://localhost:8080/blog/resources/cache/templateName.txt");
Scanner s = new Scanner(url.openStream());
name=s.nextLine();
s.close();
}
catch(IOException ex) {
ex.printStackTrace();
}*/
return name;
}
I think it can't close connection or something.
It returns me NULL even I say name="TEST"; in try construction.
FileReader is exactly that – a class that reads from files, not HTTP requests.
You're getting an invalid file path exception, which you're then ignoring in your evil empty catch block.
Instead, you should use URLConnection.
Try this
try{
URL reader=new URL("http://localhost:8080/blog/resources/cache/templateName.txt");
BufferedReader br=new BufferedReader(new InputStreamReader(reader.openStream()));
name = br.readLine();
//name="TEST";
br.close();
}catch (MalformedURLException ex) {
ex.printStackTrace();
} catch (IOException ex) {
ex.printStackTrace();
}
AFAIK, URL#openStream() internally calls URL#openConnection() which creates an instance of URLConnection and calls URLConnection#getInputStream() on it.
Related
Here is my code:
public static String readFile()
{
BufferedReader br = null;
String line;
String dump="";
try
{
br = new BufferedReader(new FileReader("dbDumpTest.txt"));
}
catch (FileNotFoundException fnfex)
{
System.out.println(fnfex.getMessage());
System.exit(0);
}
try
{
while( (line = br.readLine()) != null)
{
dump += line + "\r\n";
}
}
catch (IOException e)
{
System.out.println(e.getMessage() + " Error reading file");
}
finally
{
br.close();
}
return dump;
So eclipse is complaining about an unhandled IO exception caused by br.close();
Why would this cause an IO exception?
My second question is why eclipse doesn't complain about the following code:
InputStream is = null;
InputStreamReader isr = null;
BufferedReader br = null;
try{
// open input stream test.txt for reading purpose.
is = new FileInputStream("c:/test.txt");
// create new input stream reader
isr = new InputStreamReader(is);
// create new buffered reader
br = new BufferedReader(isr);
// releases any system resources associated with reader
br.close();
// creates error
br.read();
}catch(IOException e){
// IO error
System.out.println("The buffered reader is closed");
}finally{
// releases any system resources associated
if(is!=null)
is.close();
if(isr!=null)
isr.close();
if(br!=null)
br.close();
}
}
}
I'd appreciate it if you kept the explanation in Laymen's terms if possible. Thanks for the help in advance
Both code examples should have compiler errors complaining about an unhandled IOException. Eclipse shows these as errors in both code examples for me.
The reason is that the close method throws an IOException, a checked exception, when called in the finally block, which is outside a try block.
The fix is to use a try-with-resources statement, which is available in Java 1.7+. The resources declared are implicitly closed.
try (BufferedReader br = new BufferedReader(new FileReader("dbDumpTest.txt")))
{
// Your br processing code here
}
catch (IOException e)
{
// Your handling code here
}
// no finally necessary.
Prior to Java 1.7, you need to wrap the calls to close() in their own try-catch blocks inside the finally block. It's a lot of verbose code to ensure that everything is closed and cleaned up.
finally
{
try{ if (is != null) is.close(); } catch (IOException ignored) {}
try{ if (isr != null) isr.close(); } catch (IOException ignored) {}
try{ if (br != null) br.close(); } catch (IOException ignored) {}
}
i have a code which is to get dat from active mq and display the data on Rss feed, but the code give me no data on the feed, i get an empty list and the reason seems to be that XmlReader reader= null; i have set this line an dthe reder seems to be null during the whole execution.
public List<RssFeedMessage> readRssFeeds(#PathVariable String sourceName) {
XmlReader reader = null;
RssFeedMessage rssFeedMessage = null;
StringBuffer feedUrl = new StringBuffer("http://").append(ipaddress).append(":")
.append(port).append("/admin/queueBrowse/").append(sourceName).append("?view=rss&feedType=rss_2.0");
List<RssFeedMessage> rssFeedMessages = new ArrayList<RssFeedMessage>();
try {
URL url = new URL(feedUrl.toString());
reader = new XmlReader(url);
SyndFeed feedMsg = new SyndFeedInput().build(reader);
List<SyndEntry> feedEntries = feedMsg.getEntries();
for (SyndEntry entry : feedEntries) {
rssFeedMessage = new RssFeedMessage();
rssFeedMessage.setTitle(entry.getTitle());
rssFeedMessage.setDescription(entry.getDescription().getValue());
rssFeedMessage.setDate(OptimerUtil.simpleDateHourTimeInd.format(entry.getPublishedDate()));
rssFeedMessages.add(rssFeedMessage);
}
} catch(IOException e){
e.printStackTrace();
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (FeedException e) {
e.printStackTrace();
} finally {
if (reader != null) {
try {
reader.close();
} catch (IOException e) {
}
}
}
return rssFeedMessages;
}
}
it just exits coz reader remains null the wole time an i get io exception on reader = new XmlReader(url);
Check what feedUrl contains in line URL url = new URL(feedUrl.toString());
There is probably a problem with the string.
Also, make you you manage conditions like String equals null or unreachable, before parsing it
Goal: Print the data from a .dat file to the console using Eclipse.
(Long-Term Goal): Executable that I can pass a .dat file to and it creates a new txt file with the data formatted.
The .dat: I know the .dat file contains control points that I will need to create a graph with using ECMAScript.
Eclipse Setup:
Created Java Project
New > Class .. called the Class FileRead
Now I have FileRead.java which is:
1/ package frp;
2/
3/ import java.io.BufferedReader;
4/ import java.io.File;
5/ import java.io.FileReader;
6/
7/ public class FileRead {
8/
9/ public static void main(String[] args) {
10/ FileReader file = new FileReader(new File("dichromatic.dat"));
11/ BufferedReader br = new BufferedReader(file);
12/ String temp = br.readLine();
13/ while (temp != null) {
14/ temp = br.readLine();
15/ System.out.println(temp);
16/ }
17/ file.close();
18/ }
19/
20/ }
Please note this approach was borrowed from here: https://stackoverflow.com/a/18979213/3306651
1st Challenge: FileNotFoundException on LINE 10
Screenshot of Project Explorer:
QUESTION: How to correctly reference the .dat file?
2nd Challenge: Unhandled exception type IOException LINES 12, 14, 17
QUESTION: How to prevent these exceptions?
Thank you for your time and effort to help me, I am recreating Java applets using only JavaScript. So, I'm looking to create java tools that extract data I need to increase productivity. If you are interested in phone/web app projects involving JavaScript, feel free to contact me 8503962891
1. Without changing your code, you must place the file in the project's root folder.
Otherwise, reference it as src/frp/dichromatic.dat
2. Doing something like this:
public static void main(String[] args) {
FileReader file = null;
try {
file = new FileReader(new File("dichromatic.dat"));
} catch (FileNotFoundException e1) {
System.err.println("File dichromatic.dat not found!");
e1.printStackTrace();
}
BufferedReader br = new BufferedReader(file);
String line;
try {
while ((line = br.readLine()) != null) {
System.out.println(line);
}
} catch (IOException e) {
System.err.println("Error when reading");
e.printStackTrace();
} finally {
if (br != null) {
try {
br.close();
} catch (IOException e) {
System.err.println("Unexpected error");
e.printStackTrace();
}
}
}
}
3. Creation of a new txt file "formatted". In this example, the formatting will be settings the characters to uppercase.
public static void main(String[] args) {
FileReader file = null;
BufferedWriter bw = null;
File outputFile = new File("output.formatted");
try {
file = new FileReader(new File("dichromatic.dat"));
} catch (FileNotFoundException e1) {
System.err.println("File dichromatic.dat not found!");
e1.printStackTrace();
}
try {
bw = new BufferedWriter(new FileWriter(outputFile));
} catch (IOException e1) {
System.err.println("File is not writtable or is not a file");
e1.printStackTrace();
}
BufferedReader br = new BufferedReader(file);
String line;
String lineformatted;
try {
while ((line = br.readLine()) != null) {
lineformatted = format(line);
bw.write(lineformatted);
// if you need it
bw.newLine();
}
} catch (IOException e) {
System.err.println("Error when processing the file!");
e.printStackTrace();
} finally {
if (br != null) {
try {
br.close();
} catch (IOException e) {
System.err.println("Unexpected error");
e.printStackTrace();
}
}
if (bw != null) {
try {
bw.close();
} catch (IOException e) {
System.err.println("Unexpected error");
e.printStackTrace();
}
}
}
}
public static String format(String line) {
// replace this with your needs
return line.toUpperCase();
}
I would strongly recommend spending some time reading through the Java Trails Tutorials. To answer your specific question, look at Lesson: Exceptions.
To oversimplify, just wrap the file-handling code in a try...catch block. By example:
package frp;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
public class FileRead {
public static void main(String[] args) {
try {
FileReader file = new FileReader(new File("dichromatic.dat"));
BufferedReader br = new BufferedReader(file);
String temp = br.readLine();
while (temp != null) {
temp = br.readLine();
System.out.println(temp);
}
file.close();
} catch (FileNotFoundException fnfe) {
System.err.println("File not found: " + fnfe.getMessage() );
} catch (IOException ioe) {
System.err.println("General IO Error encountered while processing file: " + ioe.getMessage() );
}
}
}
Note that ideally, your try...catch should wrap the smallest possible unit of code. So, wrap the FileReader separately, and "fail-fast" if the file isn't found, and wrap the readLine loop in its own try...catch. For more examples and a better explanation of how to deal with exceptions, please reference the link I provided at the top of this answer.
Edit: issue of file path
Not finding the file has to do with the location of the file relative to the root of the project. In your original post, you reference the file as "dichromatic.dat" but relative to the project root, it is in "src/frp/dichromatic.dat". As rpax recommends, either change the string that points to the file to properly reference the location of the file relative to the project root, or move the file to project root and leave the string as-is.
I have developed a java code in eclipse.My code reads data from a .txt file by using server_ip. I have created an executable jar file of the code and then created an .exe file using launch4j. The .exe file shows data if I run it in my laptop,but it does not show any data if I run it in other pc. then it shows null point exception. my operating system is windows 7-32 bit. I am giving my code here. please give me solutions.
package remotedata;
import java.awt.*;
import java.net.;
import java.io.;
public class remotedataread extends Frame
{
public static void main(String[] args)
throws InterruptedException, IOException{
BufferedReader br = null;
TextArea FileText =
new TextArea(" Content of the File \'temp1.txt\' :");
try
{
URL url =
new URL("file://server_ip/path_file.txt");
InputStream is = url.openStream();
br = new BufferedReader(new InputStreamReader(is));
/* String line = null;
while (true) {
line = br.readLine();
if (line == null) {
//wait until there is more of the file for us to read
Thread.sleep(1000);
}
else {
System.out.println(line);
}
}*/
}
catch (MalformedURLException e)
{
System.out.println("Bad URL");
}
catch (IOException e)
{
System.out.println("IO Error : "+e.getMessage());
}
FileText.setBackground(Color.white);
FileText.append(String.valueOf('\n'));
Frame f = new Frame("server data");
f.setSize(200,200);
f.add(FileText);
f.setVisible(true);
try
{
String s;
s=null;
boolean eof = false;
//while (true) {
s = br.readLine();
System.out.println("Time Temperature");
while( !eof )
{
FileText.append(s + String.valueOf('\n'));
try
{
s = br.readLine();
if ( s == null )
{
// eof = true;
// br.close();
Thread.sleep(1000);
}
else{
//System.out.println("Time Temperature");
System.out.println(s);
}
}
catch (EOFException eo)
{
eof = true;
}
catch (IOException e)
{
System.out.println("IO Error : "+e.getMessage());
}
}
//}
}
catch (IOException e)
{
System.out.println("IO Error : "+e.getMessage());
}
}
}
Maybe , you're application is not able to connect to the other node ..hence its throwing a NullPointer exception .Make sure that computers are in the Network
your prolem seems to be here:
URL url =
new URL("file://server_ip/path_file.txt");
InputStream is = url.openStream();
br = new BufferedReader(new InputStreamReader(is));
the url "file://server_ip/path_file.txt" is valid on your laptop, but not on other pc's
public void tokenize(){
// attempt creating a reader for the input
reader = this.newReader();
while((line = reader.readLine())!=null){
tokenizer = new StringTokenizer(line);
while(tokenizer.hasMoreTokens()){
toke = (tokenizer.nextToken().trim());
this.tokenType(toke);
//System.out.println(this.tokenType(toke));
}
}
}
private BufferedReader newReader(){
try {//attempt to read the file
reader = new BufferedReader(new FileReader("Input.txt"));
}
catch(FileNotFoundException e){
System.out.println("File not found");
}
catch(IOException e){
System.out.println("I/O Exception");
}
return reader;
}
I thought I had handled it within newReader() but it appears to be unreachable. Eclipse recommends a throws but I don't understand what that's doing, or if it's even solving the problem?
Appreciate the help!
If you don't know how to handle an IOException in this method, then it means that it's not the responsibility of the method to handle it, and it should thus be thrown by the method.
The reader should be closed in this method, though, since this method opens it:
public void tokenize() throws IOException {
BufferedReader reader = null;
try {
// attempt creating a reader for the input
reader = this.newReader();
...
}
finally {
if (reader != null) {
try {
reader.close();
}
catch (IOException e) {
// nothing to do anymore: ignoring
}
}
}
}
Also, note that unless your class is itself a kind of Reader wrapping another reader, and thus has a close method, the reader shouldn't be an instance field. It should be a local variable as shown in my example.