I have the following problems:
I would like to call a function from another class so I added this line of code
Function1 func = new Function1(); and I get an error saying
Function1 (Context) in Function1 cannot be applied to ()
Furthermore, relating to this function and its error, I intend calling the aforementioned function which takes a JSON object and a Filename as parameters and it returns a file, however, when I enter it, I get the following error
Wrong 2nd argument type, found Java.lang.String required Java.io.File
The code in question is this:
JSONObject export = jsonArray1.getJSONObject(index);
File file = func.exportToFile(export, "Export.json");
The fuction in question starts like this:
public void exportToFile(JSONObject objectToExport, File fN)
{
String output = objectToExport.toString();
file_ = fN;
if (!file_.exists()) {
try {
file_.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
}
try{
FileOutputStream fOut = new FileOutputStream(file_);
fOut.write(output.getBytes());
fOut.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
N.B.: I have tried to call the function like this:
File file = func.exportToFile(export, func.file);
but I only get the error saying incompatible types
Required Java.io.file
Found Void
What have I done wrong?
this func.exportToFile(export, func.file); will not return anything since exportToFile it's a void method .
change your method to make it return file this way :
public File exportToFile(JSONObject objectToExport, File fN) {
String output = objectToExport.toString();
file_ = fN;
if (!file_.exists()) {
try {
file_.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
}
try{
FileOutputStream fOut = new FileOutputStream(file_);
fOut.write(output.getBytes());
fOut.close();
return file_;
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
Related
I'm working on appending objects to a binary file. My professor has provided an "appendable" output stream class for us to use on this assignment, and from my understanding this is what should prevent a corrupted header. However, I'm still getting a corrupted header when I attempt to open the binary file. The name of the file is test.dat and as far as I can tell the program writes the data just fine, but as soon as I try reading from it everything goes out the window.
fileName is a data field in the same class these methods are defined in and is defined as follows File filename = new File("test.dat");
If anyone could point me in the right direction that would be fantastic! Thanks in advance
My Code
/**
Writes a pet record to the file
#param pets The pet record to write
*/
public static void writePets(PetRecord pet){
AppendObjectOutputStream handle = null;
try{
handle = new AppendObjectOutputStream(new FileOutputStream(fileName, true));
handle.writeObject(pet);
handle.flush();
} catch (IOException e){
System.out.println("Fatal Error!");
System.exit(0);
} finally {
try{
handle.close();
} catch (IOException e){
e.printStackTrace();
}
}
}
/**
Reads all pets from the file so long as the user continues to enter "next"
*/
public static void readPets(){
Scanner keys = new Scanner(System.in);
String input = "";
ObjectInputStream handle = null;
PetRecord pet = null;
try{
handle = new ObjectInputStream(new FileInputStream(fileName)); // stack trace points here
do{
try{
pet = (PetRecord) handle.readObject();
System.out.println("\n" + pet);
System.out.println("[*] type \"next\" to continue");
input = keys.nextLine();
} catch (IOException e){
System.out.println("\t[*] No More Entries [*]");
e.printStackTrace();
break;
}
} while (input.matches("^n|^next"));
handle.close();
} catch (ClassNotFoundException e){
System.out.println("The dat file is currupted!");
} catch (IOException e){
System.out.println("\t[*] No Entries! [*]");
e.printStackTrace();
}
}
Provided class:
public class AppendObjectOutputStream extends ObjectOutputStream
{
// constructor
public AppendObjectOutputStream( OutputStream out ) throws IOException
{
// this constructor just calls the super (parent)
super(out);
}
#Override
protected void writeStreamHeader() throws IOException
{
// this forces Java to clear the previous header, re-write a new header,
// and prevents file corruption
reset();
}
}
Stack Track:
java.io.StreamCorruptedException: invalid stream header: 79737200
at java.io.ObjectInputStream.readStreamHeader(ObjectInputStream.java:808)
at java.io.ObjectInputStream.<init>(ObjectInputStream.java:301)
at UIHandle.readPets(UIHandle.java:381)
at UIHandle.list(UIHandle.java:79)
at UIHandle.command(UIHandle.java:103)
at UIHandle.mainUI(UIHandle.java:40)
at UIHandle.main(UIHandle.java:405)
Turns out it helps if you make sure a file exits before appending to it.
The problem wasn't with reading the file, but attempting to append to a file when it wasn't there. The fix was a simple if/else to check to see if the file existed. If it doesn't exist then write the file as usual, if it does exist then use the custom append class.
/**
Writes a pet record to the file
#param pet The pet record to write
*/
public static void writePet(PetRecord pet){
if (fileName.exists()){
AppendObjectOutputStream handle = null;
try{
handle = new AppendObjectOutputStream(new FileOutputStream(fileName, true));
handle.writeObject(pet);
handle.flush();
} catch (IOException e){
System.out.println("Fatal Error!");
System.exit(0);
} finally {
try{
handle.close();
} catch (IOException e){
e.printStackTrace();
}
}
} else {
ObjectOutputStream handle = null;
try{
handle = new ObjectOutputStream(new FileOutputStream(fileName));
handle.writeObject(pet);
handle.flush();
} catch (IOException e){
System.out.println("Fatal Error!");
System.exit(0);
} finally {
try{
handle.close();
} catch (IOException e){
e.printStackTrace();
}
}
}
}
Currently I'm serializing an ArrayList to a file like this:
FileOutputStream fosAlarms = null;
ObjectOutputStream oosAlarms = null;
try {
fosAlarms = openFileOutput("alarms.ser", Context.MODE_PRIVATE);
oosAlarms = new ObjectOutputStream(fosAlarms);
oosAlarms.writeObject(alarms);
System.out.println("Serialisation done");
} catch (FileNotFoundException ex) {
ex.printStackTrace();
} catch (IOException ex) {
ex.printStackTrace();
} finally {
if (oosAlarms != null && fosAlarms != null) {
try {
oosAlarms.close();
fosAlarms.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
And this works as intended. But I want this method to overwrite current file (if there is any). If I remove an object from the array and serialize it again, the removed object persists. How do I do this?
Use this constructor of FileOutputStream and set append to false.
FileOutputStream(String, boolean)
So... I guess you need to change a bit your method openFileOutput.
I really don't know what to look for and if this is even possible. I am trying to code a dynamic Fileloader.
This is the code:
public static Serializable loadSerializable(Context context,
String filename, Object object) {
final String DEBUGTAG = "Loading data" ;
Serializable serializable = null;
ObjectInputStream oin = null;
try {
File file = new File(context.getFilesDir(), filename);
FileInputStream in = new FileInputStream(file);
oin = new ObjectInputStream(in);
Object readElement = oin.readObject();
serializable = (Serializable) readElement; // here I want dynamic casting
Log.d(DEBUGTAG, "Success : " + filename);
} catch (FileNotFoundException e) {
Log.d(DEBUGTAG, "File not found");
} catch (StreamCorruptedException e) {
Log.d(DEBUGTAG, "Stream Corrupted");
} catch (IOException e) {
Log.d(DEBUGTAG, "IOException");
} catch (ClassNotFoundException e) {
Log.d(DEBUGTAG, "Class not Found");
} catch (NullPointerException e) {
Log.d(DEBUGTAG, "NullPointer - File does not exist yet");
} finally {
if (oin != null)
try {
oin.close();
} catch (IOException e) {
Log.d(DEBUGTAG, "IOException - Stream not closed");
}
}
return serializable;
}
What I want to do now is instead of creating a new method for every single object I want to use the 3rd argument (object or whatever) for the type casting.
So I could write
String myString = loadSerializable(this, test.dat, String) or
ArrayList<Fragment> = loadSerializable(this, test.dat, ArrayList<Fragment>) and so on....
Help appreciated
Something like
public static <T> T loadSerializable(Context context, String filename) {
// ...
T t = (T) readElement;
// ...
return t;
}
I have an object in charge of opening a file on HDFS to write. This object renames the file it just wrote once the close() method is invoked.
The mechanism works when running in local mode, but it fails to rename the file in cluster mode.
//Constructor
public WriteStream() {
path = String.format("in_progress/file");
try {
OutputStream outputStream = fileSystem.create(new Path(hdfs_path+path), new Progressable() {public void progress() { System.out.print("."); }
});
writer = new BufferedWriter(new OutputStreamWriter(outputStream));
} catch (IOException e) {
e.printStackTrace();
}
}
public void close() {
String newPath = String.format("%s_dir/%s_file", date, timestamp);
try {
fileSystem.rename(new Path(hdfs_path+path), new Path(hdfs_path+newPath));
writer.close();
} catch (IOException e) {
e.printStackTrace();
}
}
Did you experience that before ?
Apparently FileSystem.rename(Path) creates missing directories on the path when executed in local mode, but it does not when run in cluster mode.
This code works in both modes:
public void close() {
String dirPath = String.format("%s_dir/", date, timestamp);
String newPath = String.format("%s_dir/%s_file", date, timestamp);
try {
fileSystem.mkdir(new Path(hdfs_path+dirPath));
fileSystem.rename(new Path(hdfs_path+path), new Path(hdfs_path+newPath));
writer.close();
} catch (IOException e) {
e.printStackTrace();
}
}
Just curious, but how can you rename a file that officially doesn't exist (because you're still writing at that point)?
The fix is to rename after the file has been completed. That is, when you invoked the close method.
So your code should look like this:
public void close() {
String newPath = String.format("%s_dir/%s_file", date, timestamp);
try {
writer.close();
fileSystem.rename(new Path(hdfs_path+path), new Path(hdfs_path+newPath));
} catch (IOException e) {
e.printStackTrace();
}
}
I'm trying to read ObjectOutputStream from a file and convert it to an arraylist.
This whole thing is happening inside a method which should read the file and return the array list:
public static List<Building> readFromDatabase(){
String fileName="database.txt";
FileInputStream fileIStream=null;
ObjectInputStream in=null;
List<Building> buildingsArr=null;
try
{
fileIStream = new FileInputStream(fileName);
in = new ObjectInputStream(fileIStream);
buildingsArr=(ArrayList<Building>)in.readObject();
}
catch(IOException e)
{
e.printStackTrace();
}
catch(ClassNotFoundException e)
{
Console.printPrompt("ArrayList<Building> class not found.");
e.printStackTrace();
}
finally{
Console.printPrompt("Closing file...");
close(in);
close(fileIStream);
return buildingsArr;
}
}
Java tells me that this is dangerous.
What are the alternatives?
I can't put the return in the "try" block because it won't do it / it won't close files in the "finally" block.
I need to both make sure files will be closed, and return the array list I created as well.
Any ideas?
I can't put the return in the "try" block because it won't do it / it
won't close files in the "finally" block.
Wrong, finally block would still execute if you put return in try block. Thus you can return in your try block.
try
{
//your code
return buildingsArr;
}
catch(IOException e)
{
e.printStackTrace();
}
catch(ClassNotFoundException e)
{
Console.printPrompt("ArrayList<Building> class not found.");
e.printStackTrace();
}
finally{
Console.printPrompt("Closing file...");
close(in);
close(fileIStream);
}
I would suggest starting to use Java 7, and the try with resources clause. http://docs.oracle.com/javase/tutorial/essential/exceptions/tryResourceClose.html
Ex:
static String readFirstLineFromFile(String path) throws IOException {
try (BufferedReader br = new BufferedReader(new FileReader(path))) {
return br.readLine();
}
}
You must either throw an Exception or return a value:
All you need to prove this is comment out the return "File Not Found" after the finally block and see that it won't compile.
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
public class ReturnFinallyExample
{
public static void main(final String[] args)
{
returnFinally();
}
private static String returnFinally()
{
try
{
final File f = new File("that_does_not_exist!");
final FileInputStream fis = new FileInputStream(f);
return "File Found!";
}
catch (FileNotFoundException e)
{
e.printStackTrace();
}
finally
{
System.out.println("finally!");
}
return "File Not Found!";
}
}
You must have the return after the finally or you have to either:
declare the method to throws FileNotFoundExceptoin and re-throw the FileNotException out.
or
wrap the FileNotFoundException with throw new RuntimeException(e)