create and write files , return boolean - java

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

Related

Java FileReader method is not returning/printing all characters in file record

I am trying to write to a file thru FileWriter and then read it thru FileReader. FileWriter writes the record to file okay, but the FileReader method appears to be skipping characters while printing. I have pasted the code and the file contents and output below. Can you please help identify what I might be missing or doing wrong?
***Update -
Just realized a possibility (after posting) that the "read()" in the while statement could be reading a Character ahead the "read()" in the print statement, and hence causing every other character (beginning with the first one) to skip the print statement. Not sure though. Could that be what is happening here?
Code -
public class FileIOCharClass {
public static void main(String[] args) {
File TestChar = new File("C:\\TestChar.txt");
FileIOCharClass FileIOChar = new FileIOCharClass();
try {
FileIOChar.charWriteMethod(TestChar);
}
catch (IOException a){
System.out.println("IO Exception occured in Write method");
}
try{
FileIOChar.charReadMethod(TestChar);
}
catch (IOException b){
System.out.println("IO Exception occured in Read method");
}
}
private void charWriteMethod(File CharFileToWrite) throws IOException {
FileWriter WriteRoutine = null;
try{
WriteRoutine = new FileWriter(CharFileToWrite);
WriteRoutine.write("Line-1");
WriteRoutine.write("Line-2");
WriteRoutine.write("Line-3");
}finally {
WriteRoutine.flush();
WriteRoutine.close();
}
}
private void charReadMethod(File CharFileToRead) throws IOException {
FileReader ReadRoutine = new FileReader(CharFileToRead);
while (ReadRoutine.read() != -1){
System.out.println(((char)ReadRoutine.read()));
}
}
}
Contents of TestChar file created -
Line-1Line-2Line-3
Program print output
i
e
1
i
e
2
i
e
3
Process finished with exit code 0
The issue is that you are reading twice. Once int the while condition, and another in the block statement
while (ReadRoutine.read() != -1){
System.out.println(((char)ReadRoutine.read()));
}
Instead you can try:
int data = ReadRoutine.read();
while (data != -1) {
System.out.println((char)data);
data = ReadRoutine.read();
}

java.io.IOException: Stream closed ZipInputStream

Below is the code Snippet.
FileInputStream fin = new FileInputStream(zipFile);
ZipInputStream zin = new ZipInputStream(fin);
ZipEntry entry = null;
String routerListUCM = "";
try {
entries:
while ((entry = zin.getNextEntry()) != null) {
if (entry.getName().startsWith("routes")) {
BufferedReader in = new BufferedReader(new InputStreamReader(zin, "UTF-8"));
if (true) {
//parse the xml of the route...
DOMParser dp = new DOMParser();
dp.parse(in);
Element e = (Element) dp.getDocument().getFirstChild();
String transferid = e.getElementsByTagName("transferId").item(0).getTextContent();
System.out.println("transferId=" + transferid);
int fileid = Integer.parseInt(transferid.split("-")[1]);
System.out.println("fileid=" + transferid);
String userList = e.getElementsByTagName("userList").item(0).getTextContent();
System.out.println("userList=" + userList);
String routeList = e.getElementsByTagName("routeList").item(0).getTextContent();
System.out.println("routeList=" + routeList);
routerListUCM = routeList;
if (routeList.toLowerCase().indexOf(myname().toLowerCase()) == -1) {
//my server is not in the current route...
//so skip this route table.
continue entries;
}
}
}
}
} catch (Exception e) {
System.err.println(e.getMessage());
e.printStackTrace();
}
in some cases after "continue entries;" and trying for next loop i see "stream close Exception" :/
error:Stream closed
Stack Trace:
java.io.IOException: Stream closed
at java.util.zip.ZipInputStream.ensureOpen(ZipInputStream.java:67)
at java.util.zip.ZipInputStream.getNextEntry(ZipInputStream.java:116)
at org.parsisys.test.mina.view.SimpleFtplet$beaVersion0_1155.isTransferFinished(SimpleFtplet.java:299)
at org.parsisys.test.mina.view.SimpleFtplet.isTransferFinished(SimpleFtplet.java)
at org.parsisys.test.mina.view.SimpleFtplet.beaAccessisTransferFinished(SimpleFtplet.java)
at org.parsisys.test.mina.view.SimpleFtplet$beaVersion0_1155.onUploadEnd(SimpleFtplet.java:208)
at org.parsisys.test.mina.view.SimpleFtplet.onUploadEnd(SimpleFtplet.java)
at org.apache.ftpserver.ftplet.DefaultFtplet.afterCommand(DefaultFtplet.java:89)
at org.parsisys.test.mina.view.SimpleFtplet.afterCommand(SimpleFtplet.java)
at org.apache.ftpserver.ftpletcontainer.impl.DefaultFtpletContainer.afterCommand(DefaultFtpletContainer.java:144)
at org.apache.ftpserver.impl.DefaultFtpHandler.messageReceived(DefaultFtpHandler.java:220)
at org.apache.ftpserver.listener.nio.FtpHandlerAdapter.messageReceived(FtpHandlerAdapter.java:61)
at org.apache.mina.core.filterchain.DefaultIoFilterChain$TailFilter.messageReceived(DefaultIoFilterChain.java:716)
at org.apache.mina.core.filterchain.DefaultIoFilterChain.callNextMessageReceived(DefaultIoFilterChain.java:434)
at org.apache.mina.core.filterchain.DefaultIoFilterChain.access$1200(DefaultIoFilterChain.java:46)
at org.apache.mina.core.filterchain.DefaultIoFilterChain$EntryImpl$1.messageReceived(DefaultIoFilterChain.java:796)
at org.apache.ftpserver.listener.nio.FtpLoggingFilter.messageReceived(FtpLoggingFilter.java:85)
at org.apache.mina.core.filterchain.DefaultIoFilterChain.callNextMessageReceived(DefaultIoFilterChain.java:434)
at org.apache.mina.core.filterchain.DefaultIoFilterChain.access$1200(DefaultIoFilterChain.java:46)
at org.apache.mina.core.filterchain.DefaultIoFilterChain$EntryImpl$1.messageReceived(DefaultIoFilterChain.java:796)
at org.apache.mina.core.filterchain.IoFilterEvent.fire(IoFilterEvent.java:75)
at org.apache.mina.filter.logging.MdcInjectionFilter.filter(MdcInjectionFilter.java:136)
at org.apache.mina.filter.util.CommonEventFilter.messageReceived(CommonEventFilter.java:70)
at org.apache.mina.core.filterchain.DefaultIoFilterChain.callNextMessageReceived(DefaultIoFilterChain.java:434)
at org.apache.mina.core.filterchain.DefaultIoFilterChain.access$1200(DefaultIoFilterChain.java:46)
at org.apache.mina.core.filterchain.DefaultIoFilterChain$EntryImpl$1.messageReceived(DefaultIoFilterChain.java:796)
at org.apache.mina.filter.codec.ProtocolCodecFilter$ProtocolDecoderOutputImpl.flush(ProtocolCodecFilter.java:427)
at org.apache.mina.filter.codec.ProtocolCodecFilter.messageReceived(ProtocolCodecFilter.java:245)
at org.apache.mina.core.filterchain.DefaultIoFilterChain.callNextMessageReceived(DefaultIoFilterChain.java:434)
at org.apache.mina.core.filterchain.DefaultIoFilterChain.access$1200(DefaultIoFilterChain.java:46)
at org.apache.mina.core.filterchain.DefaultIoFilterChain$EntryImpl$1.messageReceived(DefaultIoFilterChain.java:796)
at org.apache.mina.core.filterchain.IoFilterEvent.fire(IoFilterEvent.java:75)
at org.apache.mina.core.session.IoEvent.run(IoEvent.java:63)
at org.apache.mina.filter.executor.OrderedThreadPoolExecutor$Worker.runTask(OrderedThreadPoolExecutor.java:780)
at org.apache.mina.filter.executor.OrderedThreadPoolExecutor$Worker.runTasks(OrderedThreadPoolExecutor.java:772)
at org.apache.mina.filter.executor.OrderedThreadPoolExecutor$Worker.run(OrderedThreadPoolExecutor.java:714)
at java.lang.Thread.run(Thread.java:748)
Please Help Me....................................................................................................................................................................................................................................................
It seems that your outermost BufferedReader object closes your nested streams (in particular ZipInputStream). Try to move your BufferedReader initalization code higher the looping logic.
Also this topic might be helpful: closing nested streams.
Update:
Ok, now everything is clear. Implementation code of DOMParser class shows clearly that parse method closes underlying InputStream source (just an excerpt of finally block):
} finally {
this.parser.reader.close();
}
What can be done in this situation is hacking your BufferedReader which is passed to DOMParser object. Here's an example:
public class HackedReader extends BufferedReader {
public HackedReader(InputStreamReader inputStreamReader) {
super(inputStreamReader);
}
#Override
public void close() {
// Close method doesn't do anything, that's the main sense of overriding.
}
// But you know exact method which will close your underlying stream.
public void hackedClose() throws IOException {
super.close();
}
}
I found using the org.apache.poi.util.CloseIgnoringInputStream worked for me. I was able to wrap the ZipInputStream that I was passing into another method.
For example:
ExcelUtility.getLineCount(new CloseIgnoringInputStream(zipStream)
If you can implemet a logic to understand if there aren't more "routes" to read, at the end of If block you can insert a break instruction to exit the while block and avoid to attempt to read the closed stream

Catching Same IOException Inside Catch IOException Block

My Android code is behaving funny. The input stream should and does throw an IOException, which correctly causes control to go to // read an error stream. The error stream is read correctly and the debugger steps to return error_message with the error_message variable containing expected characters read from error stream. It then correctly steps to the // no op in the finally block, which I added just for kicks.
And then, it steps to return "all hope lost";!! Which then, instead of returning to the caller, steps into some Android system code that throws a SecurityException with a message about lack of content permissions.
Removing the finally block has no impact -- the bug still happens. The streams being read are from an HTTP URL Connection. No problems if server returns 200 but if server returns 400 it goes through the weird path described above and tries to throw the weird SecurityException.
try {
// read an input stream into message
return message;
} catch (IOException outer) {
try {
// read an error stream into error_message
return error_message;
} catch (IOException inner) {
return "all hope lost";
}
} finally {
// no op, just to step debugger
}
Update: Posting exact code and debug trace.
try {
/*x*/ BufferedReader buffered_reader =
new BufferedReader(
new InputStreamReader(
new BufferedInputStream(http_url_connection.getInputStream())));
StringBuilder string_builder = new StringBuilder();
String line;
for (line = buffered_reader.readLine();
line != null;
line = buffered_reader.readLine()) {
string_builder.append(line);
}
return string_builder.toString();
} catch (IOException io_exception) {
this.io_exception = io_exception;
BufferedReader buffered_reader =
new BufferedReader(
new InputStreamReader(
new BufferedInputStream(http_url_connection.getErrorStream())));
StringBuilder string_builder = new StringBuilder();
try {
for (String line = buffered_reader.readLine();
line != null;
line = buffered_reader.readLine()) {
string_builder.append(line);
}
/*y*/ String error_message = "server error: " + string_builder.toString();
return error_message;
} catch (IOException exception) {
String level_2_error_message = "level 2 error: " + exception.getMessage();
return level_2_error_message;
} finally {
return "foo";
}
}
Line /*x*/ causes the jump to the first catch as expected. All lines up to /*y*/ are then executed as expected. Then the weird thing is that line /*y*/ does not complete and control immediately goes to either the next catch block if there is no finally or to the finally. If there is a finally then it does not to got the last catch block.
The contents of the string buffer on /*y*/ line look perfectly fine -- a 20 character string from the server.
You say that an exception is being thrown by line /* y */
By my reading of that line of code, the following are plausible explanations:
The exception is a NullPointerException because string_builder is null. But it can't be.
The exception is an OutOfMemoryError because you don't have enough free space for the toString() call to create the new String object.
It is possible that StringBuilder is not java.lang.StringBuilder but some class you wrote yourself. In that case, any exception is possible.
However, I can't see how you would end up in the second IOException handler.
Apart from that, the only other likely explanation is that that source code does not match the code that you are actually executing; e.g. you forgot to recompile something, or you forgot to redeploy after your last compilation.
For what it is worth, your return in your finally is almost certainly a mistake.
It means that you will return "foo" instead of either of the error messages.
If (for example) string_builder.toString() did throw an NPE or OOME, then the return would squash it.
A finally with a return can have non-intuitive behaviour. It is certainly NOT something you should do "for debugging"!!!

reading variables buried in java exception handling

I am writing a function to take a text file and count how many lines it has while outputting the lines to an array of strings. Doing this I have several exceptions I need to look out for. The class function has several variables that should have a scope throughout the function but when I write a value to the function inside of an exception, the return statement cannot find it. I've moved the declaration around and nothing helps
The value returned "h5Files" "Might not have been initialized" Since I don't know how long the array will be I cannot initialize it to a certain length. I do this within the code and I need a way to tell the return statement that I now have a values
Here is the code
public String[] ReadScanlist(String fileIn){
int i;
String directory ="c:\\data\\"; // "\" is an illegal character
System.out.println(directory);
int linereader = 0;
String h5Files[];
File fileToRead = new File(directory + fileIn);
System.out.println(fileToRead);
try {
FileInputStream fin = new FileInputStream(fileToRead); // open this file
}
catch(FileNotFoundException exc) {
System.out.println("File Not Found");
}
try{
//read bytes until EOF is detected
do {
FileReader fr = new FileReader(fileToRead);// Need to convert to reader
LineNumberReader lineToRead = new LineNumberReader(fr); // Use line number reader class
//
while (lineToRead.readLine() != null){
linereader++;
}
linereader = 0;
lineToRead.setLineNumber(0); //reset line number
h5Files = new String[linereader];
while (lineToRead.readLine() != null){
h5Files[linereader] = lineToRead.readLine(); // deposit string into array
linereader++;
}
return h5Files;
}
while(i !=-1); // When i = -1 the end of the file has been reached
}
catch(IOException exc) {
System.out.println("Error reading file.");
}
try{
FileInputStream fin = new FileInputStream(fileToRead);
fin.close(); // close the file
}
catch(IOException exc) {
System.out.println("Error Closing File");
}
return h5Files;
}
Your code is very very odd. For example these two blocks make no sense:
try {
FileInputStream fin = new FileInputStream(fileToRead); // open this file
}
catch(FileNotFoundException exc) {
System.out.println("File Not Found");
}
try{
FileInputStream fin = new FileInputStream(fileToRead);
fin.close(); // close the file
}
catch(IOException exc) {
System.out.println("Error Closing File");
}
I don't know what you think they do, but besides the first one leaking memory, they do nothing at all. The comments are more worrying, they suggest that you need to do more reading on IO in Java.
Deleting those blocks and tidying the code a (moving declarations, formatting) gives this:
public String[] ReadScanlist(String fileIn) {
String directory = "c:\\data\\";
String h5Files[];
File fileToRead = new File(directory + fileIn);
try {
int i = 0;
do {
FileReader fr = new FileReader(fileToRead);
LineNumberReader lineToRead = new LineNumberReader(fr);
int linereader = 0;
while (lineToRead.readLine() != null) {
linereader++;
}
linereader = 0;
lineToRead.setLineNumber(0);
h5Files = new String[linereader];
while (lineToRead.readLine() != null) {
h5Files[linereader] = lineToRead.readLine();
linereader++;
}
return h5Files;
} while (i != -1);
} catch (IOException exc) {
System.out.println("Error reading file.");
}
return h5Files;
}
My first bone of contention is the File related code. First, File abstracts from the underlying OS, so using / is absolutely fine. Second, there is a reason File has a File, String constructor, this code should read:
File directory = new File("c:/data");
File fileToRead = new File(directory, fileIn);
But it should really be using the new Path API anyway (see below).
So, you declare h5Files[]. You then proceed to read the whole file to count the lines. You then assign h5Files[] to an array of the correct size. Finally you fill the array.
If you have an error anywhere before you assign h5Files[] you have not initialised it and therefore cannot return it. This is what the compiler is telling you.
I don't know what i does in this code, it is assigned to 0 at the top and then never reassigned. This is an infinite loop.
So, you need to rethink your logic. I would recommend throwing an IOException if you cannot read the file. Never return null - this is an anti-pattern and leads to all those thousands of null checks in your code. If you never return null you will never have to check for it.
May I suggest the following alternative code:
If you are on Java 7:
public String[] ReadScanlist(String fileIn) throws IOException {
final Path root = Paths.get("C:/data");
final List<String> lines = Files.readAllLines(root.resolve(fileIn), StandardCharsets.UTF_8);
return lines.toArray(new String[lines.size()]);
}
Or, if you have Java 8:
public String[] ReadScanlist(String fileIn) throws IOException {
final Path root = Paths.get("C:/data");
try (final Stream<String> lines = Files.lines(root.resolve(fileIn), StandardCharsets.UTF_8)) {
return lines.toArray(String[]::new);
}
}
Since I don't know how long the array will be I cannot initialize it
to a certain length.
I don't think an array is the correct solution for you then - not to say it can't be done, but you would be re-inventing the wheel.
I would suggest you use a LinkedList instead, something like:
LinkedList<String> h5Files = new LinkedList<>();
h5Files.add(lineToRead.readLine());
Alternatively you could re-invent the wheel by setting the array to an arbritary value, say 10, and then re-size it whenever it gets full, something like this:
h5Files = new String[10];
if (linereader = h5Files.size())
{
String[] temp = h5Files;
h5Files = new String[2 * linereader];
for (int i = 0; i < linereader; i++)
{
h5Files[i] = temp[i];
}
}
Either one of these solutions would allow you to initialize the array (or array alternative) in a safe constructor, prior to your try block, such that you can access it if any exceptions are thrown
Here is your problem. Please take a look on digested version of your code with my comments.
String h5Files[]; // here you define the variable. It still is not initialized.
try{
..................
do {
h5Files = new String[linereader]; // here you initialize the variable
} while(i !=-1); // When i = -1 the end of the file has been reached
..................
catch(IOException exc) {
// if you are here the variable is still not initialized
System.out.println("Error reading file.");
}
// you continue reading file even if exception was thrown while opening the file
I think that now the problem is clearer. You try to open the file and count lines. If you succeed you create array. If not (i.e. when exception is thrown) you catch the exception but still continue reading the file. But in this case you array is not initialized.
Now how to fix this?
Actually if you failed to read the file first time you cannot continue. This may happen for example if file does not exist. So, you should either return when first exception is thrown or just do not catch it at all. Indeed there is nothing to do with the file if exception was thrown at any phase. Exception is not return code. This is the reason that exceptions exist.
So, just do not catch exceptions at all. Declare your method as throws IOException and remove all try/catch blocks.

Do I need to care about type of encoding if the JSON file is going to share across different platforms

Currently, I'm using gson, to perform serialization on Objects. It works pretty fine in single platform (Windows).
However, if I were gonna to share the json file across different platforms (Windows, Linux, Mac, Android), do I need to specific type of encoding (UTF-8) being used? (There will be foreign language characters in json file)? Or, the default encoding used by BufferedWriter/BufferedReader will be same across all platforms?
public static boolean write(A a, File file) {
final Gson gson = new Gson();
String string = gson.toJson(a);
try {
//If the constructor throws an exception, the finally block will NOT execute
BufferedWriter writer = new BufferedWriter(new FileWriter(file));
try {
writer.write(string);
} finally {
//no need to check for null
//any exceptions thrown here will be caught by
//the outer catch block
writer.close();
}
} catch (IOException ex){
return false;
}
return true;
}
public static A load(File file) {
// Copy n paste from newInstance.
final Gson gson = new Gson();
try {
//If the constructor throws an exception, the finally block will NOT execute
BufferedReader reader = new BufferedReader(new FileReader(file));
try {
return gson.fromJson(reader, A.class);
} finally {
//no need to check for null
//any exceptions thrown here will be caught by
//the outer catch block
reader.close();
}
} catch (IOException ex){
}
return null;
}
Just to add to it, FileReader and FileWriter are platform specific. Prefer ObjectStreams instead. Again, my score does not permit me to put it as a comment:(

Categories

Resources