Which Exception Do I Throw in This Case? - java

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;
}

Related

Use try-with-resources or close this "BufferedReader" in a "finally" clause

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 :-)

Modify stream reader class to read from file instead of System.in

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 csvReader java code and it is returning only the second line after the header over and over again till the last line index

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.

Access external files

Am using nio2 to read the external file in my desktop using eclipse. I am getting the exception for the following code.
"java.nio.file.NoSuchFileException: C:\Users\User\Desktop\JEE\FirstFolder\first.txt"
Kindly advise how to resolve it? Tried using command prompt also. Getting the same exception.
public class ReadingExternalFile {
public static void main(String[] args) {
Path p1= Paths.get("C:\\Users\\User\\Desktop\\FirstFolder\\first.txt");
System.out.println(p1.toString());
System.out.println(p1.getRoot());
try(InputStream in = Files.newInputStream(p1);
BufferedReader reader = new BufferedReader(new InputStreamReader(in)))
{
System.out.println("Inside try");
String line=null;
while((line=reader.readLine())!=null){
if (!line.equals("")) {
System.out.println(line);
}
//System.out.println(line);
}
} catch (IOException e) {
System.out.println( e);
}
}
}
I dont understand why you are using a Path object, you can simply make the file using the File object and just using the string as the path, and then wraping it in a file reader object then wrapping that in a buffered reader, the end should look something like this:
public static void main(String[] args) {
try {
File file = new File("C:\\Users\\User\\Desktop\\FirstFolder\\first.txt");
FileReader fr = new FileReader(file);
BufferedReader bfr = new BufferedReader(fr);
System.out.println(bfr.readLine());
bfr.close();
} catch (IOException e){
e.printStackTrace();
}
}
don't forget to close your streams after reading and writing, also use readable names (don't do what I've done, use meaningful names!)
Try below code hope this will help you.
Path p1= Paths.get("C:\\Users\\user\\Desktop\\FirstFolder\\first.txt");
try(
BufferedReader reader = Files.newBufferedReader(p1, Charset.defaultCharset()))
{
System.out.println("Inside try");
String line=null;
while((line=reader.readLine())!=null){
if (!line.equals("")) {
System.out.println(line);
}
//System.out.println(line);
}
} catch (IOException e) {
System.out.println( e);
}
Try this.
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
public class BufferedReaderExample {
public static void main(String[] args) {
BufferedReader br = null;
try {
String sCurrentLine;
br = new BufferedReader(new FileReader("C:\\Users\\User\\Desktop\\FirstFolder\\first.txt"));
while ((sCurrentLine = br.readLine()) != null) {
System.out.println(sCurrentLine);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (br != null)br.close();
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
}
public static void main(String[] args) {
try {
File file = new File("C:\\Users\\User\\Desktop\\FirstFolder\\first.txt");
FileReader freader = new FileReader(file);
BufferedReader bufreader = new BufferedReader(freader);
System.out.println(bufreader.readLine());
bufreader.close();
} catch (IOException e){
e.printStackTrace();
}
}

How to check for valid sentence using index values in a file in Java

I have a following Begin and End indexes of sentences in a file.
Begin:1583 End:1631
Begin:2284 End:2324
Now i have to check whether these indexes are existed in a valid sentence by reading a particular file.I have tried with BreakIterator.But i did not understand how can i check the above indexes are existed in a valid sentence.
The code i have tried is
public class Breakiterator {
public static void main(String[] args) {
BufferedReader br = null;
String sCurrentLine = null;
String l=null;
try {
br = new BufferedReader(new FileReader("C:/test.txt "));
while ((sCurrentLine = br.readLine()) != null) {
BreakIterator i=BreakIterator.getSentenceInstance(Locale.GERMANY);
i.setText(sCurrentLine);
for(int s=i.first(), e=i.next(); e>=0; s=e, e= i.next())
{
System.out.println("Sentence: from "+s+" to "+e+" \""+sCurrentLine.substring(s, e)+'"');
}
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (br != null)br.close();
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
}
Try this. Modify your regular expression as per your requirement
public static final String VALID_LINE_REG_EXP = "\\w+:\\d+.\\w+:\\d+";
public static void main(String args[]) {
BufferedReader br = null;
String sCurrentLine = null;
String l = null;
boolean isValid;
try {
br = new BufferedReader(new FileReader("D:/Shamse.txt "));
while ((sCurrentLine = br.readLine()) != null) {
System.out.println(sCurrentLine.trim().matches(VALID_LINE_REG_EXP));
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (br != null) {
br.close();
}
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
I have written this code assuming that your file will contains values in TEXT:NUMBER TEXT:NUMBER you can modify this regular expression as per your requirement

Categories