I have this method in Java, which is called within another method's try block. importFormat returns the class with assigned values (//do what is needed) in the try block. The method should read a file line by line. In case the method call to the method with try block is called more times than are the lines in a file, the importFormat() should return null.
I tried to check it with if block, although it doesn't do much and the ClassName is always returned. It seems the class stores always a first line from the file.
private ClassName importFormat(BufferedReader br) throws IOException, ParseException {
String out;
Track t = new ClassName();
if((out = br.readLine()) == null) return null;
//do what is needed
}else{
t = null; //here I unsuccessfully tried to force the method to again return null, no luck
System.err.print(out);
throw new ParseException("", 0);
}
return t;
}
I have tried also the br.ready() method, it didn't make any difference
EDIT: I noticed I have reproduced the code incorrectly, I'm sorry for that. Here it should be clearer
Minimal reproducible code:
private ClassName foo(BufferedReader br) throws IOException {
ClassName t = new ClassName();
String out = null;
out = br.readLine();
if(out.equals(null)) return null; //handle the case where there's no more line to read
if(/*!string red from BufferedReader.isEmpty()*/){
//do something
}else{
t = null; //ensure that null would be returned
//do something more unrelated to this question
}
return t;
}
I dont realy understand your question but I think you should not compare like this:
if((out = br.readLine()) == null) return null;
To compare string in java, let use str1.equals(str2) instead. So I think you should try:
if(out.equals(br.readLine())) {
//do sth here because "out" exists in BufferReader.
} else {
System.out.println("Continue searching...\n");
}
return t;
Related
Write a public static method named q1 that takes no parameters and has return type boolean. This method will attempt to open a file named "location.txt" and returns true if the file exists and contains the String "statistical" as a sub-String on any line, and false if "statistical" is not found. This method will also return false if "location.txt" does not exist.
This is what I did, Im not sure how to put this as a boolean.
public static boolean q1() {
String filename = x;
// creating file name location.txt
try {
String x = "location.txt";
System.out.print("location.txt file has been created");
String textToWrite = "statistical";
Files.write(Paths.get(x), textToWrite.getBytes());
}
catch (IOException e) {
boolean r = false;
return r;
}
BufferedReader br = new BufferedReader(new FileReader("location.txt"));
String textToWrite;
while ((textToWrite = br.readLine()) != null) {
}
return f;
}
Using the Stream API introduced in Java 8:
/**
* Returns whether the file 'location.txt' exists and any line contains the string "statistical".
*
* #return true if the file exists and any line contains "statistical", false otherwise
* #throws IOException if an I/O error occurs
*/
public static boolean q1() throws IOException {
Path path = Paths.get("location.txt");
try (Stream<String> lines = Files.lines(path)) {
return lines.anyMatch(line -> line.contains("statistical"));
} catch (FileNotFoundException e) {
return false;
} catch (UncheckedIOException e) {
// Stream wraps IOExceptions, because streams don't throw checked exceptions. Unwrap them.
throw e.getCause();
}
}
Edit: Using try-with-resource to dispose file system resources.
The returned stream encapsulates a Reader. If timely disposal of file system resources is required, the try-with-resources construct should be used to ensure that the stream's close method is invoked after the stream operations are completed.
Edit 2: Unwrapping the stream's UncheckedIOException to make it easier for the caller to handle exceptions.
After this method returns, then any subsequent I/O exception that occurs while reading from the file or when a malformed or unmappable byte sequence is read, is wrapped in an UncheckedIOException that will be thrown from the Stream method that caused the read to take place. In case an IOException is thrown when closing the file, it is also wrapped as an UncheckedIOException.
The first part of your code seems to be creating a file that satisfies the criteria given (that is, it makes the following code, and the requirements pointless). Don't do that. Read the file line-by-line. Check if the line you read contains the string you are searching for. If it does return true. Otherwise return false. Like,
public static boolean q1() {
String fileName = "location.txt", toFind = "statistical";
try (BufferedReader br = new BufferedReader(new FileReader(new File(fileName)))) {
String line;
while ((line = br.readLine()) != null) {
if (line.contains(toFind)) {
return true;
}
}
} catch (IOException e) {
e.printStackTrace();
}
return false;
}
I am having a big problem with this, now I have a class called FileRelationship, and I have two constructors with it. Class is shown below. I also overrode the equals method in this class.
public class FileRelationship {
String fileName;
String firstLink;
String secondLink;
String thirdLink;
public FileRelationship(String fileName) {
this.fileName = fileName;
}
public FileRelationship(String fileName, String firstLink, String secondLink, String thirdLink) {
this.fileName = fileName;
this.firstLink = firstLink;
this.secondLink = secondLink;
this.thirdLink = thirdLink;
}
public boolean equals(Object o) {
if(o == null) {
return false;
}
if(this == o) {
return true;
}
if(o instanceof FileRelationship) {
return this.fileName.equals(((FileRelationship)o).fileName);
}
return false;
}
}
Now I have an arrayList of FileRelationships and I want to be able to search through this list (These all use the constructor with 4 Strings in it (fileName, firstLink, secondLink, thirdLink)) Now I have a method in another class that is supposed to search this arrayList and this find the index of one that has a matching fileName. When I call this method I am only passing into the constructor with the fileName and that is all. (This is the only I can do it, I will not know the other strings).
This is how I set up the ArrayList of FileRelationships.
fileRelationships = new ArrayList<FileRelationship>();
String MasterLine;
InputStream inputStream = this.getResources().openRawResource(R.raw.masterfile);
InputStreamReader inputreader = new InputStreamReader(inputStream);
BufferedReader buffreader = new BufferedReader(inputreader);
// Creates the arrayList of all the relationships for later use of retreival.
try {
while (( MasterLine = buffreader.readLine()) != null) {
MasterLineArray = MasterLine.split(",");
String filename = MasterLineArray[0];
String choice1 = MasterLineArray[1];
String choice2 = MasterLineArray[2];
String choice3 = MasterLineArray[3];
FileRelationship fr = new FileRelationship(filename, choice1, choice2, choice3);
fileRelationships.add(fr);
}
} catch (IOException e) {
} finally {
closeQuietly(buffreader);
}
This is my method for finding the relationship and then setting it to the variable I need. I want to be able to find the index of the list and apply it to the variable.
public void findRelationship(String nextFileName) {
int pageIndex = fileRelationships.indexOf((new FileRelationship(nextFileName)));
selectedRelationship = fileRelationships.get(pageIndex);
currentPage = pageIndex;
}
EDIT : I'm sorry forgot to say what was wrong. No it doesn't work. pageIndex is returning a -1 (So in other words it isn't finding anything). I don't know what else to do, maybe use HashCode but honestly I've even looked up stuff about it and I can't really figure out how to use that either.
I really really need help on this, as this is for a school project due soon. I have most of the project done as once I get this part finished I should be almost done. Thanks.
Search like this
public void findRelationship(String nextFileName) {
for(FileRelationship file:fileRelationships)
{
if(file.firsFileName.equals(nextFileName))
{
currentPage=fileRelationships.indexOf(file);
}
}
}
list returns -1 when list doesn't contain that object. In your case you where using indexOf() obj by creating new object
int pageIndex = fileRelationships.indexOf((new FileRelationship(nextFileName)));
this is not the right way. because you are creating new object and list does not contains new object
And also make getter setter method for each fields in FileRelationship class directly accessing each field is not the good practice
I'm currently working on a simple method which converts the content of a file to a string. I saw several topics covering some detail about this question (here). However I can use the try catch or a return do_nothing as mentioned in the previous linked answer. The code:
public static String getStringFromFile(String path) throws EmptyFileException {
String data =null;
try {
BufferedReader reader = new BufferedReader(new FileReader(path));
String line;
while ((line = reader.readLine()) != null) {
data += line +"\n";
}
if (data == null) {
throw new EmptyFileException();
}
}
catch (FileNotFoundException ex) {
showExceptionMessage("File not found");
}
catch (IOException ex) {
showExceptionMessage("Can't read the file");
}
return(data);
}
private static void showExceptionMessage(String message) {
JOptionPane.showMessageDialog(null, message, "ERROR", JOptionPane.ERROR_MESSAGE);
}
So what would be "better" throwing an exception if the file is empty or just using return doNothing() (were doNothing is the function that does nothing, makes sense right? hahah).
Is this a good way to avoid null return?
Yes, always return "existing" object instead of null if you can. Null Object Pattern is a good aproach to avoid that.
So what would be "better" throwing an exception if the file is empty
or just using return doNothing()
In your case throwing an exception is overkill for me. You should throw an exception when you don't expect particular behaviour. Have a look at FileNotFoundException. You always expect that file exists so it's a good choice to throw exception when you can't find this file.
So as metioned above null is bad, so why can't you return empty string? :) In this case it will work like Null Object Pattern, like placeholder :)
I need to read a text file line by line till I find a specific string. I'm using BufferedReader.readLine() but when I debug I find that it starts from the third line in the file and skips lines after that.
Here is my code:
try {
reader = new BufferedReader(new FileReader(path));
String line1 = null;
while ((line1 = reader.readLine()) != null) {
if (line1.toString() == invocation0) {
found = true;
return false;
} else if (line1 == invocation1) {
found = true;
return true;
}
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if (reader != null)
try {
reader.close();
} catch (IOException e) {
}
}
I would really appreciate any help, as I tried many different solutions for this and still can't solve this issue.
the content of the file is like:
.//============================================================================
.// File: abc.mark
.// Description: anything
.// Notice: anything
.// .//============================================================================
.invoke RemoveClass("Properties",0)
if(line1.equals(invocation0))
Use equals() method for String value comparison.
Also, instead of return within the if, you can use a break. This is just a suggestion though.
BufferedReader should not be skipping the anything. Unfortunately you are the one who is making read method to skip the line. The equlaity operator == will not compare the content of any two strings, rather it compares whether they are of same object. You could possibly avoid it in two ways.
Call the intern() on invocation0 (line1 object should have been interned before anyway)
More precisely use equals method line1.equals(invocaton0)
This link may be of some help for you to understand it better.
I'm writing a file reader that returns an object and I'd like it to warn on parse errors and continue to the next record.
The code below is the obvious implementation of this, but involves recursing from inside the catch block. Is there any technical or stylistic reason not to do this?
public RecordType nextRecord() throws IOException{
if (reader == null){
throw new IllegalStateException("Reader closed.");
}
String line = reader.readLine();
if (line == null){
return null;
}else{
try {
return parseRecord(line);
}catch (ParseException pex){
logger.warn("Record ignored due to parse error: "
+ pex.getMessage());
//Note the recursion here
return nextRecord();
}
}
}
I would prefer to use a loop. With recursion, you never know how deep you can safely go.
String line;
while((line = reader.readLine()) != null) {
try {
return parseRecord(line);
}catch (ParseException pex){
logger.warn("Record ignored due to parse error: " + pex);
}
}
return null;
Why not replace the recursion with a loop:
public RecordType nextRecord() throws IOException {
if (reader == null) {
throw new IllegalStateException("Reader closed.");
}
for (;;) {
String line = reader.readLine();
if (line == null) {
return null;
} else {
try {
return parseRecord(line);
} catch (ParseException pex) {
logger.warn("Record ignored due to parse error: "
+ pex.getMessage());
// continue to the next record
}
}
}
}
Stylistically, I find this preferable.
Would it be cleaner to let the ParseException propagate back to the caller? The caller could then decide what to do about it.
What it seems like to me is that whatever is calling your method is going to keep calling it until the method returns null.
I would probably follow the advice of the previous posters and use a loop, however I would look at whatever is calling the method (as it is probably already using a loop), have it skip the line by looking for an exception to be thrown.