Converting Java IO Class to Android IO - java

I want to convert my IO Class from java on Eclipse to the Android API. For some reason it's not working on android!It is giving me a NullPointerException on my Println method. This class is used to create, write, read and open textfiles. My goal is to make all these methods readable on android.
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintStream;
import java.io.PrintWriter;
public class IO {
private static PrintWriter fileOut;
private static BufferedReader fileIn;
public static void createOutputFile(String fileName) {
try {
fileOut = new PrintWriter(new BufferedWriter(new FileWriter(fileName)));
} catch (IOException e) {
System.out.println("*** Cannot create file: " + fileName + " ***");
}
}
public static void openOutputFile(String fileName) {
try {
fileOut = new PrintWriter(new BufferedWriter(new FileWriter(fileName, true)));
} catch (IOException e) {
System.out.println("*** Cannot open file: " + fileName + " ***");
}
}
public static void openOutputFile2(String fileName) {
try {
fileOut = new PrintWriter(new BufferedWriter(new FileWriter(fileName, false)));
} catch (IOException e) {
System.out.println("*** Cannot open file: " + fileName + " ***");
}
}
public static void print(String text) {
fileOut.print(text);
}
public static void println(String text) {
fileOut.println(text);
//System.out.println(text);
}
public static void closeOutputFile() {
fileOut.close();
}
public static void openInputFile(String fileName) {
try {
fileIn = new BufferedReader(new FileReader(fileName));
//System.out.println("opening " + fileName);
} catch (FileNotFoundException e) {
System.out.println("***Cannot open " + fileName + "***");
}
}
public static String readLine()
// throws IOException
// Note: if there's an error in this method it will return IOException
{
try {
return fileIn.readLine();
} catch (IOException e) {
e.printStackTrace();
return "errors";
}
}
public static void closeInputFile() {// throws IOException
// Note: if there's an error in this method it will return IOException
try {
fileIn.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}

If you're getting a NullPointerException in println then that would be because 'fileOut' is null.
public static void println(String text) {
fileOut.println(text);
//System.out.println(text);
}
You're actually reacting on your second error because you've ignored the first one. In all cases where you set fileOut you're swallowing (effectively hiding) the error. E.g.
public static void openOutputFile(String fileName) {
try {
fileOut = new PrintWriter(new BufferedWriter(new FileWriter(fileName, true)));
} catch (IOException e) {
//Don't do this, it makes debugging much more difficult.
//Because the root problem is hidden.
//So now you have 2 problems to solve.
//And you've thrown away the information that might have
//helped to solve the problem in the first place.
System.out.println("*** Cannot open file: " + fileName + " ***");
}
}
Stop hiding errors, if something goes wrong you need to find out about it. Because invariably, ignoring errors results in more complex errors later down the line.
Fix you bad exception handling, and you'll be able to track down the root problem (probably file not found or a permission error).

Related

Why doesn't it work correctly to write in the file?

I am currently trying to program a small API, but with my writeToFile method, even if I use true in the method, it deletes everything that is in the file and only writes in the text of the user (#param text).
What did I do wrong ? I tried to print the string, but it appears to be empty. If I only use the readFile method of mine, it reads out the whole file correctly.
Need help.
package at.tornaduuu.usefullapi.files;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
public class FileUtils {
public static void writeToFile(String text, File file, boolean keepIndexText) {
try {
String indexText = "";
FileWriter fw = new FileWriter(file);
if (keepIndexText) {
indexText = FileUtils.readFile(file);
System.out.println(indexText);
FileUtils.clearFile(file);
fw.write(indexText + text);
fw.close();
}
else {
fw.write(text);
fw.close();
}
}
catch (IOException e) {
e.printStackTrace();
}
}
public static void clearFile(File file) {
try {
FileWriter fw = new FileWriter(file);
fw.write("");
fw.close();
}
catch (IOException e) {
e.printStackTrace();
}
}
public static String readFile(File file) {
String fileIndex = "";
int unicode;
try {
FileReader fr = new FileReader(file);
try {
while ((unicode = fr.read()) != -1) {
fileIndex += (char) unicode;
}
fr.close();
}
catch (IOException e) {
e.printStackTrace();
}
}
catch (FileNotFoundException e) {
e.printStackTrace();
}
return fileIndex;
}
}
You are not appending to file, you are just rewriting it. That's because FileWriter is not set to append. You can change this:
FileWriter fw = new FileWriter(file); //rewrites file every time write() method is called
to:
FileWriter fw = new FileWriter(file,true); //append text in file when write() is called
and it should work.
You are calling FileWriter(File) which in turn will call FileOutputStream(String name, append = False). So your file is getting truncated before you read content.
There is another constructor FileWriter(File file, boolean append) that you can use with keepIndexText, in such case your FileUtils.clearFile(file); is pretty useless.

Want a code to be written without throwing exception

I have the below piece of code.
import java.io.*;
public class FileTest {
public static void main(String[] args) throws IOException {
WriteLinesToFile("miss.txt","This is a special file");
}
public static void WriteLinesToFile(String outputFileName, String lineConverted) throws IOException {
File f = new File(outputFileName);
if (f.createNewFile()) {
System.out.println("File is created!");
FileWriter writer = new FileWriter(f);
writer.write(lineConverted);
writer.close();
} else {
System.out.println("File already exists.");
FileWriter writer = new FileWriter(f);
writer.write(lineConverted);
writer.close();
}
}
}
I need the same logic, without throwing exception. Could someone tell me how to do this?
You could handle your exception with a try{} catch(IOException e){}
But it's important to handle the exception, because otherwise your program will do something, but not what you want.
import java.io.*;
public class FileTest {
public static void main(String[] args)
{
writeLinesToFile("miss.txt", "This is a special file");
}
public static void writeLinesToFile(String outputFileName, String lineConverted){
File f = new File(outputFileName);
try {
if (f.createNewFile()) {
System.out.println("File is created!");
FileWriter writer = new FileWriter(f);
writer.write(lineConverted);
writer.close();
} else {
System.out.println("File already exists.");
FileWriter writer = new FileWriter(f);
writer.write(lineConverted);
writer.close();
}
}
catch(IOException e){
//Handle your error
}
}}
But you can't cut out the exceptions at all, because handling files in java throws always exceptions (For example if the file could not be found).

Repeatedly Writing to a File

I'm a moderately-experienced C++ guy slowly learning Java. I'm writing a program which needs to do the following:
Create a simple text file, default directory is fine
As the program runs, periodically write one line of data to the file. Depending on a number of factors, the program may write to the file once or a million times. There is no way of knowing which write will be the last.
I've been researching different ways to do this, and this is the working code I've come up with. There are two files, "PeteProgram.java" and "PeteFileMgr.java" :
/*
"PeteProgram.java"
*/
import java.io.*;
import java.lang.String;
public class PeteProgram {
public static void main(String[] args) throws IOException {
String PeteFilename="MyRecordsFile.txt";
Writer writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(PeteFilename), "utf-8"));
PeteFileMgr MyPeteFileMgr = new PeteFileMgr(writer);
MyPeteFileMgr.AddThisString(writer, "Add this line #1\n");
MyPeteFileMgr.AddThisString(writer, "Add this line #2\n");
MyPeteFileMgr.AddThisString(writer, "Add this line #3\n");
}
}
//=====================================================================================================
//=====================================================================================================
/*
"PeteFileMgr.java"
*/
import java.io.*;
public class PeteFileMgr {
public PeteFileMgr(Writer writer) {
try {
writer.write("File created!");
} catch (IOException ex) {
// report
} finally {
try {writer.close();} catch (Exception ex) {}
}
}
void AddThisString(Writer writer, String AddThis) {
try {
writer.append(AddThis);
} catch (IOException ex) {
// report
} finally {
try {writer.close();} catch (Exception ex) {}
}
}
}
The initial creation of the file works just fine. However, the to-be-added lines are not written into the file. Because the program compiles and runs with no errors, I assume the program tries to write the added lines, fails, and throws an exception. (Unfortunately, I am working with a primitive compiler/debugger and can't see if this is the case.)
Does anyone spot my mistake?
Many thanks!
-P
That's because you're not flushing the Writer. You should call flush from time to time. Also, you should close your Writer at the end of your app, not after writing content into it. close method automatically flushes the contents of the writer.
So, this is how your code should look like:
public class PeteProgram {
public static void main(String[] args) {
String peteFilename = "MyRecordsFile.txt";
//here's when the physical file is created
Writer writer = null;
try {
writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(peteFilename), "utf-8"));
PeteFileMgr peteFileMgr = new PeteFileMgr(writer);
peteFileMgr.addThisString(writer, "Add this line #1\n");
peteFileMgr.addThisString(writer, "Add this line #2\n");
peteFileMgr.addThisString(writer, "Add this line #3\n");
} catch (IOException e) {
//handle the exception
//basic handling
e.printStacktrace();
} finally {
//this is a must!
try { writer.close(); } catch(IOException silent) { }
}
}
}
public class PeteFileMgr {
public PeteFileMgr(Writer writer) {
try {
//this method is not creating the physical file
writer.write("File created!");
} catch (IOException ex) {
// report
} finally {
//remove this call to close
//try {writer.close();} catch (Exception ex) {}
}
}
public void addThisString(Writer writer, String addThis) {
try {
writer.append(addThis);
} catch (IOException ex) {
// report
} finally {
//remove this call to close
//try {writer.close();} catch (Exception ex) {}
}
}
}
Or if using Java 7 or superior using the try-with-resources:
public class PeteProgram {
public static void main(String[] args) {
String peteFilename = "MyRecordsFile.txt";
//here's when the physical file is created
try (Writer writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(peteFilename), "utf-8"))) {
PeteFileMgr peteFileMgr = new PeteFileMgr(writer);
peteFileMgr.addThisString(writer, "Add this line #1\n");
peteFileMgr.addThisString(writer, "Add this line #2\n");
peteFileMgr.addThisString(writer, "Add this line #3\n");
} catch (IOException e) {
//handle the exception
//basic handling
e.printStacktrace();
}
}
}

Java - Reading from and Writing to a Text File

I'm successfully able to read from and write to a sample text file in Java. However, when I try to read from the file, it always throws a NoSuchElementException when it reaches the end of the file. I've modified the code to catch this exception by printing "Reached end of file," but I was wondering if that was normal; I don't feel like it is and I feel like I'm missing something.
Any help is appreciated. Here is my code:
MyFileWriter.java
import java.io.*;
public class MyFileWriter {
public static void main(String[] args) {
File file = new File("MyFile.txt");
PrintWriter out = null;
try {
out = new PrintWriter(file);
out.write("This is a text file.");
} catch(IOException e) {
e.printStackTrace();
System.out.println("IOException: " + e.getMessage());
} finally {
out.flush();
out.close();
}
}
}
MyFileReader.java
import java.io.*;
import java.util.*;
public class MyFileReader {
public static void main(String[] args) {
File file = new File("MyFile.txt");
Scanner scan = null;
try {
scan = new Scanner(file);
while(true) {
String next = scan.nextLine();
if(next != null) {
System.out.println(next);
}
else {
break;
}
}
} catch(IOException e) {
e.printStackTrace();
System.out.println("IOException: " + e.getMessage());
} catch(NoSuchElementException e) {
System.out.println("***Reached end of file***");
} finally {
scan.close();
}
}
}
Instead of while(true) in the reader, use while( scan.hasNextLine() )

Java : Problems accessing and writing to file

I was testing out writing to files with this code:
package files;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;
public class FileTest1
{
public static void main(String[] args)
{
try
{
try
{
File f = new File("filetest1.txt");
FileWriter fWrite = new FileWriter(f);
BufferedWriter fileWrite = new BufferedWriter(fWrite);
fileWrite.write("This is a test!");
}
catch(FileNotFoundException e)
{
System.out.print("A FileNotFoundException occurred!");
e.printStackTrace();
}
}
catch(IOException e)
{
System.out.println("An IOException occurred!:");
e.printStackTrace();
}
}
}
Nothing happens when it is executed.
"This is a test!" is not written, nor the StackTrace or the "A/An [exception] occurred!"...
I don't know what's causing the problem. I have fileTest1.txt in the package right under the file...
A BufferedWriter does just that, it buffers the output before it is written to the destination. This can make the BufferedWriter faster to use as it doesn't have to write to a slow destination, like a disk or socket, straight away.
The contents will be written when the internal buffer is to full, you flush the Writer or close the writer
Remember, if you open it, you should close it...
For example...
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
public class TestFileWriter {
public static void main(String[] args) {
try {
BufferedWriter fileWrite = null;
try {
File f = new File("filetest1.txt");
System.out.println("Writing to " + f.getCanonicalPath());
FileWriter fWrite = new FileWriter(f);
fileWrite = new BufferedWriter(fWrite);
fileWrite.write("This is a test!");
fileWrite.flush();
} catch (FileNotFoundException e) {
System.out.print("A FileNotFoundException occurred!");
e.printStackTrace();
} finally {
try {
// Note, BufferedWriter#close will also close
// the parent Writer...
fileWrite.close();
} catch (Exception exp) {
}
}
} catch (IOException e) {
System.out.println("An IOException occurred!:");
e.printStackTrace();
}
try {
BufferedReader br = null;
try {
File f = new File("filetest1.txt");
System.out.println("Reading from " + f.getCanonicalPath());
FileReader fReader = new FileReader(f);
br = new BufferedReader(fReader);
String text = null;
while ((text = br.readLine()) != null) {
System.out.println(text);
}
} catch (FileNotFoundException e) {
System.out.print("A FileNotFoundException occurred!");
e.printStackTrace();
} finally {
try {
// Note, BufferedWriter#close will also close
// the parent Writer...
br.close();
} catch (Exception exp) {
}
}
} catch (IOException e) {
System.out.println("An IOException occurred!:");
e.printStackTrace();
}
}
}
If you are using Java 7, you may like to take a look at try-with-resources
After
fileWrite.write("This is a test!");
you have to flush() the writer. To avoid leaking of resources you should also close() the writer (which automatically flushes it).
So you need to add:
fileWrite.close();
Use BufferedWriter.flush() and BufferedWriter.close(). Additional info here http://docs.oracle.com/javase/7/docs/api/java/io/BufferedWriter.html
You must call close() or at least flush() on the writer in order for the buffer to be really written to the file.

Categories