I'm attempting to fetch data from an url and dump it into "content" instance variable. Both the url and the content should be initialized in the contructor. The hasNextLine() and nextLine() are also involved but being completely new to Java I can't make sense of that. Here's the code:
public class NewsFinder {
// Instance variables
private String url;
private String content;
private Scanner s;
// Getter methods
public String getUrl() {
return url;
}
public String getContent() {
return content;
}
// Constructor
public NewsFinder(String url) {
this.url = url;
try {
Scanner s = new Scanner(new URL(url).openStream());
if (s.hasNextLine()) {
this.s = s.nextLine();
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public boolean isInNews(Object o) {
if (((String) o).contains(content)) {
return true;
} else {
return false;
}
}
Any suggestions?
Scanner s = new Scanner(new URL(url).openStream());
if (s.hasNextLine()) {
this.s = s.nextLine();
}
Logically, this part of code should be replaced by :
Scanner s = new Scanner(new URL(url).openStream());
while (s.hasNextLine()) {
this.s += s.nextLine();
}
Personnaly, I would use an InputStream and a BufferedReader to achieve this.
Example
URL url; InputStream is; BufferedReader br; String line; StringBuilder sb;
try{
url = new URL("http://stackoverflow.com");
is = url.openStream();
br = new BufferedReader(new InputStreamReader(is));
sb = new StringBuilder();
while ((line = br.readLine()) != null){
sb.append(line);
}
}catch(Exception e){
e.printStackTrace();
}finally{
try{
if(is != null){
is.close();
}catch(Exception e){
e.printStackTrace();
}
}
Related
Been looking for a way to fix this issue. Read all the previous answers but none helped me out.
Could it be any error with SonarQube?
public class Br {
public String loader(String FilePath){
BufferedReader br;
String str = null;
StringBuilder strb = new StringBuilder();
try {
br = new BufferedReader(new FileReader(FilePath));
while ((str = br.readLine()) != null) {
strb.append(str).append("\n");
}
} catch (FileNotFoundException f){
System.out.println(FilePath+" does not exist");
return null;
} catch (IOException e) {
e.printStackTrace();
}
return strb.toString();
}
}
You are not calling br.close() which means risking a resource leak. In order to reliably close the BufferedReader, you have two options:
using a finally block:
public String loader(String FilePath) {
// initialize the reader with null
BufferedReader br = null;
String str = null;
StringBuilder strb = new StringBuilder();
try {
// really initialize it inside the try block
br = new BufferedReader(new FileReader(FilePath));
while ((str = br.readLine()) != null) {
strb.append(str).append("\n");
}
} catch (FileNotFoundException f) {
System.out.println(FilePath + " does not exist");
return null;
} catch (IOException e) {
e.printStackTrace();
} finally {
// this block will be executed in every case, success or caught exception
if (br != null) {
// again, a resource is involved, so try-catch another time
try {
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return strb.toString();
}
using a try-with-resources statement:
public String loader(String FilePath) {
String str = null;
StringBuilder strb = new StringBuilder();
// the following line means the try block takes care of closing the resource
try (BufferedReader br = new BufferedReader(new FileReader(FilePath))) {
while ((str = br.readLine()) != null) {
strb.append(str).append("\n");
}
} catch (FileNotFoundException f) {
System.out.println(FilePath + " does not exist");
return null;
} catch (IOException e) {
e.printStackTrace();
}
return strb.toString();
}
Seems like you just want to read all lines from a file. You could use this:
public String loader(String FilePath) {
try(Scanner s = new Scanner(new File(FilePath).useDelimiter("\\A")) {
return s.hasNext() ? s.next() : null;
} catch(IOException e) {
throw new UncheckedIOException(e);
}
}
The code you wrote is indeed leaking resources as you're not closing your BufferedReader. The following snippet should do the trick:
public String loader(String filePath){
String str = null;
StringBuilder strb = new StringBuilder();
// try-with-resources construct here which will automatically handle the close for you
try (FileReader fileReader = new FileReader(filePath);
BufferedReader br = new BufferedReader(fileReader);){
while ((str = br.readLine()) != null) {
strb.append(str).append("\n");
}
}
catch (FileNotFoundException f){
System.out.println(filePath+" does not exist");
return null;
}
catch (IOException e) {
e.printStackTrace();
}
return strb.toString();
}
If you're still having issues with this code, then yes, it's SonarQubes fault :-)
I have a problem in time while reading from a file because I use in this case scanner.
I have a code fast input but without using a file
so I want to add a file to my code or recommend to me a fast input method using file
public class FastReader {
BufferedReader br;
StringTokenizer st;
public FastReader() {
br = new BufferedReader(new InputStreamReader(System.in));
}
String next() {
while (st == null || !st.hasMoreElements()) {
try {
st = new StringTokenizer(br.readLine());
} catch (IOException e) {
e.printStackTrace();
}
}
return st.nextToken();
}
int nextInt() {
return Integer.parseInt(next());
}
long nextLong() {
return Long.parseLong(next());
}
double nextDouble() {
return Double.parseDouble(next());
}
String nextLine() {
String str = "";
try {
str = br.readLine();
} catch (IOException e) {
e.printStackTrace();
}
return str;
}
}
As was suggested in the comments, you can modify the class to handle file input by adding a parameter to the constructor that allows injecting any InputStream:
public FastReader(InputStream in) {
br = new BufferedReader(new InputStreamReader(in));
}
Then you can use the reader as follows:
FastReader systemInReader = new FastReader(System.in);
FastReader fileReader = new FastReader(new FileInputStream("/path/to/the/file"));
I have this code:
public class ReadCSVFile {
public ArrayList<Efo> readFile(File file, Efo efo) {
ArrayList<Efo> efoList = new ArrayList<Efo>();
Logger log;
BufferedReader br = null;
try {
FileReader fr = new FileReader(file);
br = new BufferedReader(fr);
br.readLine();
String line=null;
while((line=br.readLine())!=null){
String[] csvEfo = line.split("\\|");
String midID = csvEfo[1];
String memID = csvEfo[2];
efo.setMidAppID(midID);
efo.setMidMemberID(memID);
efo = new Efo();
efoList.add(efo);
line = br.readLine();
}
} catch (FileNotFoundException e) {
System.out.println(e.getMessage());
} catch (IOException e) {
System.out.println(e.getMessage());
}
finally {
try {
if (br!= null) {
//flush and close both "input" and its underlying FileReader
br.close();
}
}
catch (IOException ex) {
ex.printStackTrace();
}
}
return efoList;
}
}
and I'm calling this arraylist here:
public class BEQ_Launcher extends CMSProcessBaseImpl{
BEQ_Launcher() {}
public void launchData(String appNode, boolean isOverride, boolean isCreateWI) {
try {
efo = new Efo();
csvInputFile = new ReadCSVFile();
csvContents = new ArrayList();
csvContents = csvInputFile.readFile(testFile, efo);
if(csvContents.size() > 0){
for (int i=0; i < csvContents.size(); i++) {
System.out.println(efo.getMidMemberID()","efo.getMidAppID());
}
}
other codes...
It is only outputting the line after the header over and over again..
What should i do?
When i remove the parameters in readFile and just declare Efo efo = new Efo inside the readFile.. getters are returning null when called..
Efo() class only have all the variable declarations and the getters and setters..
line = br.readLine();
You need to remove the final readLine() from this loop. Otherwise you will throw away every even-numbered line. while ((line = br.readLine()) != null) does all the line reading you need.
I'm having a problem with this block of code here. I want to be able to display the output of a file that only contains the words "LANTALK". My catch doesn't seem to be right though. Do you know which exception I should throw in this case?
try {
sc = new Scanner(filename);
while(sc.hasNext()) {
String line=sc.nextLine();
if(line.contains("LANTALK"))
System.out.println(line);
}
} catch (FileNotFoundException e) {
System.out.println("The file \""+log+"\" was not found");
}
just use e.printStackTrace()
try
{
sc = new Scanner(filename);
while(sc.hasNext())
{
String line=sc.nextLine();
if(line.contains("LANTALK"))
System.out.println(line);
}
} catch (FileNotFoundException e)
{
e.printStackTrace();
}
It's all depends on how this method and possible exceptions would be processed.
Probably you should not throw an exception but return boolean that represents if the file contains that keyword. For example:
private boolean isValidFile(final String filename) throws IOException
{
FileReader fr = new FileReader(filename);
BufferedReader br = new BufferedReader(fr);
String line;
while((line = br.readLine()) != null)
{
if(line.contains("LANTALK"))
{
return true;
}
}
return false;
}
i want to get text from stream . but i dont get it correctly .
Everything works good , but i only need to know how to get PrintWriter into string .
i tried to convert PrintWriter with the function .ToString() but it doesnt work correctly , is print differen string .
Java :
private ServerSocket Server_Socket;
private static final int CLIENTRPORT = 5000;
Socket socket = null;
class Connect_To_Client implements Runnable
{
#Override
public void run()
{
try
{
Server_Socket = new ServerSocket(CLIENTRPORT);
socket = Server_Socket.accept();
}
catch (IOException e)
{
e.printStackTrace();
}
}
}
public BufferedReader input;
public String Get_Message_From_Server()
{
PrintWriter out = null;
String out_string = "";
try
{
input = new BufferedReader(new InputStreamReader(socket.getInputStream()));
System.out.println(input);
}
catch (IOException e)
{
e.printStackTrace();
}
return(out_string);//the text - problem
}
To read from a buffered reader do something like this
BufferedReader reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
StringBuilder sb = new StringBuilder();
String line = reader.readLine();
while (line != null) {
sb.append(line);
line = reader.readLine();
}
return sb.toString();