Google drive return empty files - android

I am making a app which access files from google drive. I am using this link to acess the files from google drive. The methodFiles.List request = service.files().list(); return {} for me all the time. i am posting my all code here.
private Drive getDriveService() {
try {
GoogleAccountCredential credential = GoogleAccountCredential
.usingOAuth2(MainActivity.this, DriveScopes.DRIVE_FILE);
credential.setSelectedAccountName("Sachinkamboj1989#gmail.com");
drive = new Drive.Builder(AndroidHttp.newCompatibleTransport(),
new GsonFactory(), credential).build();
drive.children();
drive.files();
new Thread(new Runnable() {
#Override
public void run() {
// TODO Auto-generated method stub
try {
retrieveAllFiles1(drive);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}).start();
} catch (Exception e) {
e.printStackTrace();
}
return drive;
}
private static List<File> retrieveAllFiles1(Drive service)
throws IOException {
List<File> result = new ArrayList<File>();
Files.List request = service.files().list();
do {
try {
FileList files = request.execute();
System.out.println(files);
result.addAll(files.getItems());
request.setPageToken(files.getNextPageToken());
} catch (IOException e) {
System.out.println("An error occurred: " + e);
request.setPageToken(null);
}
} while (request.getPageToken() != null
&& request.getPageToken().length() > 0);
// System.out.println(result);
return result;
}
Method to access file is

Related

How to save an application's data?

I have written a Web View app, which logs you into 12 different sites (sign in) which works pretty fine. However, i am trying to figure out a way to backup my web view's data (so that all the login credentials are saved) to SD card. the only way i have found is to copy the root/data/data/com.example/your app folder.
How do i copy this folder somewhere to my SD card using root command on the click of a button?
this is how i access and delete the data folder
private void clear() {
String cmd = "pm clear com.wagtailapp";
ProcessBuilder pb = new ProcessBuilder().redirectErrorStream(true)
.command("su");
Process p = null;
try {
p = pb.start();
} catch (IOException e) {
e.printStackTrace();
}
StreamReader stdoutReader = new StreamReader(p.getInputStream(),
CHARSET_NAME);
stdoutReader.start();
out = p.getOutputStream();
try {
out.write((cmd + "\n").getBytes(CHARSET_NAME));
} catch (UnsupportedEncodingException e1) {
e1.printStackTrace();
} catch (IOException e1) {
e1.printStackTrace();
}
try {
out.write(("exit" + "\n").getBytes(CHARSET_NAME));
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
out.flush();
} catch (IOException e) {
e.printStackTrace();
}
try {
p.waitFor();
} catch (InterruptedException e) {
e.printStackTrace();
}
String result = stdoutReader.getResult();
}
}
streamreader.java
class StreamReader extends Thread {
private InputStream is;
private StringBuffer mBuffer;
private String mCharset;
private CountDownLatch mCountDownLatch;
StreamReader(InputStream is, String charset) {
this.is = is;
mCharset = charset;
mBuffer = new StringBuffer("");
mCountDownLatch = new CountDownLatch(1);
}
String getResult() {
try {
mCountDownLatch.await();
} catch (InterruptedException e) {
e.printStackTrace();
}
return mBuffer.toString();
}
#Override
public void run() {
InputStreamReader isr = null;
try {
isr = new InputStreamReader(is, mCharset);
int c = -1;
while ((c = isr.read()) != -1) {
mBuffer.append((char) c);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (isr != null)
isr.close();
} catch (IOException e) {
e.printStackTrace();
}
mCountDownLatch.countDown();
}
}
}

UnknownHostException causes Fatal error in AsyncTask

I have the following code, and all works fine when I can connect to the server:
public void getXMLData()
{
if (skipUpdate)
{
skipUpdate=false;
return;
}
skipUpdate=true;
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
int SERVERPORT=0;
try {
SERVERPORT = Integer.parseInt(prefs.getString("pref_key_port_1","Port"));
} catch (NumberFormatException e) {
txtStatus.setText("Invalid Port Number");
return;
}
String SERVERHOST = prefs.getString("pref_key_host_1","127.0.0.1");
String PASSWORD = prefs.getString("pref_key_pass_1", "password");
try {
XMLFetcherTask myXMLFetcherTask = new XMLFetcherTask(SERVERHOST,SERVERPORT,PASSWORD);
myXMLFetcherTask.execute();
} catch (Exception e) {
txtStatus.setText("Error "+e.getMessage());
return;
}
skipUpdate=false;
}
public class XMLFetcherTask extends AsyncTask<Void, Void, Void> {
String dstAddress;
int dstPort;
String response = "";
String password="";
XMLFetcherTask(String addr, int port, String pass){
dstAddress = addr;
dstPort = port;
password=pass;
}
#Override
protected Void doInBackground(Void... arg0) {
Socket socket = null;
try {
socket = new Socket(dstAddress, dstPort);
PrintWriter out = new PrintWriter(new BufferedWriter(
new OutputStreamWriter(socket.getOutputStream())),
true);
out.println(password);
response="";
BufferedReader input = new BufferedReader(new InputStreamReader(socket.getInputStream()));
while (response.toLowerCase().indexOf("</response>")<0)
{
response+=input.readLine();
}
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
txtStatus.setText("UnknownHostException: " + e.getMessage());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
txtStatus.setText("IOException: " + e.getMessage());
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
txtStatus.setText("Exception: " + e.getMessage());
} finally{
try {
socket.close();
} catch (IOException e) {
// TODO Auto-generated catch block
//txtStatus.setText("Exception Finally: " + e.getMessage());
}
}
return null;
}
#Override
protected void onPostExecute(Void result) {
if( !(response.substring(0,5).equalsIgnoreCase("<resp") || response.substring(0,5).equalsIgnoreCase("<?xml")) ) //!response.substring(0,5).equalsIgnoreCase("<?xml") ||
{
txtStatus.setText("Server response doesn't look XML, please check password: '"+response.substring(0,5)+"'");
} else {
lastXMLData=response;
txtStatus.setText("Resp Len: " + response.length());
skipUpdate=false;
updateFragmentListeners();
}
super.onPostExecute(result);
}
}
Now, when I get UnknownHostException, the app force close with following stack trace:
07-29 15:52:08.754 1525-1538/android.process.acore V/BackupServiceBinder﹕ doBackup() invoked
07-29 15:52:08.766 1525-1538/android.process.acore E/DictionaryBackupAgent﹕ Couldn't read from the cursor
07-29 16:29:55.178 1525-1534/android.process.acore E/StrictMode﹕ A resource was acquired at attached stack trace but never released. See java.io.Closeable for information on avoiding resource leaks.
java.lang.Throwable: Explicit termination method 'close' not called
at dalvik.system.CloseGuard.open(CloseGuard.java:184)
at android.os.ParcelFileDescriptor.<init>(ParcelFileDescriptor.java:180)
at android.os.ParcelFileDescriptor$1.createFromParcel(ParcelFileDescriptor.java:916)
at android.os.ParcelFileDescriptor$1.createFromParcel(ParcelFileDescriptor.java:906)
at android.app.IBackupAgent$Stub.onTransact(IBackupAgent.java:71)
at android.os.Binder.execTransact(Binder.java:446)
07-29 16:29:55.178 1525-1534/android.process.acore E/StrictMode﹕ A resource was acquired at attached stack trace but never released. See java.io.Closeable for information on avoiding resource leaks.
java.lang.Throwable: Explicit termination method 'close' not called
at dalvik.system.CloseGuard.open(CloseGuard.java:184)
at android.os.ParcelFileDescriptor.<init>(ParcelFileDescriptor.java:180)
at android.os.ParcelFileDescriptor$1.createFromParcel(ParcelFileDescriptor.java:916)
at android.os.ParcelFileDescriptor$1.createFromParcel(ParcelFileDescriptor.java:906)
at android.app.IBackupAgent$Stub.onTransact(IBackupAgent.java:64)
at android.os.Binder.execTransact(Binder.java:446)
07-29 16:29:55.178 1525-1534/android.process.acore E/StrictMode﹕ A resource was acquired at attached stack trace but never released. See java.io.Closeable for information on avoiding resource leaks.
java.lang.Throwable: Explicit termination method 'close' not called
at dalvik.system.CloseGuard.open(CloseGuard.java:184)
at android.os.ParcelFileDescriptor.<init>(ParcelFileDescriptor.java:180)
at android.os.ParcelFileDescriptor$1.createFromParcel(ParcelFileDescriptor.java:916)
at android.os.ParcelFileDescriptor$1.createFromParcel(ParcelFileDescriptor.java:906)
at android.app.IBackupAgent$Stub.onTransact(IBackupAgent.java:57)
at android.os.Binder.execTransact(Binder.java:446)
I have no idea why this happen...
I tried to comment hte txtStatus.setText as normally it's not supposed to work from another thread, but no change.
Tested on android emulator with framework 22 and on my phone with framework 21.
Any idea would be welcome
Ok I manage to make it work using threads instead, here's final code:
public void getXMLData()
{
if (skipUpdate)
{
skipUpdate=false;
return;
}
skipUpdate=true;
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
int SERVERPORT=0;
try {
SERVERPORT = Integer.parseInt(prefs.getString("pref_key_port_1","Port"));
} catch (NumberFormatException e) {
txtStatus.setText("Invalid Port Number");
return;
}
String SERVERHOST = prefs.getString("pref_key_host_1","127.0.0.1");
String PASSWORD = prefs.getString("pref_key_pass_1", "password");
try {
// XMLFetcherTask myXMLFetcherTask = new XMLFetcherTask(SERVERHOST,SERVERPORT,PASSWORD);
// myXMLFetcherTask.execute();
XMLFetcherTask XMLFetcherTaskThread = new XMLFetcherTask();
XMLFetcherTaskThread.dstAddress=SERVERHOST;
XMLFetcherTaskThread.dstPort=SERVERPORT;
XMLFetcherTaskThread.password=PASSWORD;
Thread cThread = new Thread(XMLFetcherTaskThread);
cThread.start();
} catch (Exception e) {
txtStatus.setText("Error "+e.getMessage());
return;
}
skipUpdate=false;
}
public class XMLFetcherTask implements Runnable {
String dstAddress;
int dstPort;
String response = "";
String password="";
private void setStatusFromThread(final String status)
{
runOnUiThread(new Runnable() {
#Override
public void run() {
setStatus(status);
}
});
}
private void updateListenersThread()
{
runOnUiThread(new Runnable() {
#Override
public void run() {
updateFragmentListeners();
}
});
}
public void run() {
Socket socket = null;
//BufferedReader input = null;
//PrintWriter out = null;
try {
socket = new Socket(dstAddress, dstPort);
PrintWriter out = new PrintWriter(new BufferedWriter(
new OutputStreamWriter(socket.getOutputStream())),
true);
out.println(password);
response="";
BufferedReader input = new BufferedReader(new InputStreamReader(socket.getInputStream()));
while (response.toLowerCase().indexOf("</response>") < 0) {
response+=input.readLine();
}
if( !(response.substring(0,5).equalsIgnoreCase("<resp") || response.substring(0,5).equalsIgnoreCase("<?xml")) ) //!response.substring(0,5).equalsIgnoreCase("<?xml") ||
{
setStatusFromThread("Server response doesn't look XML, please check password: '" + response.substring(0, 5) + "'");
} else {
lastXMLData=response;
Date dNow = new Date( );
SimpleDateFormat ft = new SimpleDateFormat ("hh:mm:ss");
setStatusFromThread("Last update: " + ft.format(dNow));
skipUpdate=false;
updateListenersThread();
}
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
setStatusFromThread("UnknownHostException: " + e.getMessage());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
setStatusFromThread("IOException: " + e.getMessage());
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
setStatusFromThread("Exception: " + e.getMessage());
} finally{
try {
socket.close();
} catch (IOException e) {
// TODO Auto-generated catch block
//txtStatus.setText("Exception Finally: " + e.getMessage());
} catch (Exception e) {
// TODO Auto-generated catch block
}
}
}
}

android, Read content of 100-300 files from FTP folder... Hangs

I am using RetrieveFilestream method with BufferedInputStream in a for loop. I am closing all
streams after processing each file and also adding ftp complete pending command.
Every thing works as expected in my test environment with few files. But in realtime data where there are 200-300 files, it hangs somewhere.
It is not throwing any exception making it difficult to debug. Cannot debug one by one. Any help?
Here is my code Block.
public String LoopThroughFiles(FTPClient myftp, String DirectoryName)
{
boolean flag=false;
String output="";
InputStream inStream=null;
BufferedInputStream bInf= null;
StringBuilder mystring = new StringBuilder();
progressBar = (ProgressBar) findViewById(R.id.progressBar);
try {
flag= myftp.changeWorkingDirectory(DirectoryName);
if(flag==true)
{
FTPFile[] files = myftp.listFiles();
progressBar.setMax(files.length);
String fname="";
myftp.enterLocalPassiveMode();
if(files.length > 0)
{
int n=0;
for (FTPFile file : files)
{
n=n+1;
int r= progressBar.getProgress();
progressBar.setProgress(r+n);
fname=file.getName();
// String path= myftp.printWorkingDirectory();
if(fname.indexOf("txt") != -1)
{
inStream = myftp.retrieveFileStream(fname);
int reply = myftp.getReplyCode();
if (inStream == null || (!FTPReply.isPositivePreliminary(reply) && !FTPReply.isPositiveCompletion(reply))) {Log.e("error retrieving file",myftp.getReplyString()); }
bInf=new BufferedInputStream (inStream);
int bytesRead;
byte[] buffer=new byte[1024];
String fileContent=null;
while((bytesRead=bInf.read(buffer))!=-1)
{
fileContent=new String(buffer,0,bytesRead);
mystring.append(fileContent);
}
mystring.append(",");
bInf.close();
inStream.close();
boolean isSucess= myftp.completePendingCommand();
if(isSucess == false)
Log.e("error retrieving file","Failed to retrieve the stream for " + fname);
}
}
flag= myftp.changeToParentDirectory();
}
}
}
catch (java.net.UnknownHostException e) {
e.printStackTrace();
Log.e("readfile,UnknownHost",e.getMessage());
}
catch (java.io.IOException e) {
e.printStackTrace();
Log.e("readfile,IO",e.getMessage());
}
catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
Log.e("readfile,General",e.getMessage());
}
finally
{
try {
output = mystring.toString();
if(bInf != null)
bInf.close();
if(inStream != null)
inStream.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
Log.e("readfile,finallyblock",e.getMessage());
}
}
return output;
}

Filelist filelist request.execute() does not work

I want to list all the files that my google accouunts have with my app, i tried the follow piece of code which is actually from the website, but , there's error in the line " FileList fileList = request.execute(); ", it says the method execute() is undefined for the type Drive.Files.List ,i don't know how to fix it.
private void getDriveContents()
{
Thread t = new Thread(new Runnable()
{
#Override
public void run()
{
com.google.api.services.drive.Drive.Files f1 = mService.files();
Files.List request = null;
do
{
try
{
request = service.files().list().setQ("trashed=false");
FileList fileList = request.execute();
mResultList.addAll(fileList.getItems());
request.setPageToken(fileList.getNextPageToken());
} catch (UserRecoverableAuthIOException e) {
startActivityForResult(e.getIntent(), REQUEST_AUTHORIZATION);
} catch (IOException e) {
e.printStackTrace();
if (request != null)
{
request.setPageToken(null);
}
}
} while (request.getPageToken() !=null && request.getPageToken().length() > 0);
populateListView();
}
});
t.start();
}
I believe your 'request' is of incorrect type. it is supposed to be FileList, not File.List
I wasn't arguing about what you've seen. I was only trying to help since I have similar code running and tested. Here's a snippet from my "class ListDownFromGOODrive extends AsyncTask..."
import com.google.api.services.drive.model.FileList;
...
.... a lot of code here
...
GoogleAccountCredential _crd;
Drive _svc;
FileList _gooLst;
Intent _it;
String _rqst;
...
... a lot of code here
...
#Override protected Integer doInBackground(Void... nothing) {
try {
if (_crd == null)
_crd = GoogleAccountCredential.usingOAuth2(_ctx,Arrays.asList(DriveScopes.DRIVE_FILE));
if (_svc == null)
_svc = new Drive.Builder
(AndroidHttp.newCompatibleTransport(), new GsonFactory(), _crd).build();
if (_crd.getSelectedAccountName() == null) {
_it = _crd.newChooseAccountIntent();
return REQ_EMAIL;
}
_gooLst = _svc.files().list().setMaxResults(MAX_DOWN).setQ(_rqst)
.setFields("items(id,title,description,downloadUrl,thumbnailLink)").execute();
}
catch (UserRecoverableAuthIOException e){ //Log.d("atn", "LD URAIO Except->REQ_AUTH");
try { _it = e.getIntent(); } catch (Exception e1) {return ERROR;}
return REQ_AUTH;
}
catch (IOException e) { return ERROR; }
catch (Exception e) { return ERROR; }
return GOOD;
}
it returns GOOD, ERROR, REQ_AUTH(orization), or REQ_EMAIL(account)

read/write an object to file

here is the code :
my mission is to serialize an my object(Person) , save it in a file in android(privately), read the file later,(i will get a byte array), and deserialize the byta array.
public void setup()
{
byte[] data = SerializationUtils.serialize(f);
WriteByteToFile(data,filename);
}
Person p =null ;
public void draw()
{
File te = new File(filename);
FileInputStream fin = null;
try {
fin=new FileInputStream(te);
byte filecon[]=new byte[(int)te.length()];
fin.read(filecon);
String s = new String(filecon);
System.out.println("File content: " + s);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
text(p.a,150,150);
}
and my function :
public void WriteByteToFile(byte[] mybytes, String filename){
try {
FileOutputStream FOS = openFileOutput(filename, MODE_PRIVATE);
FOS.write(mybytes);
FOS.close();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("done");
}
it is returning a filenotfoundexception .
(i am new at this, so please be patient and understanding)
EDIT ::this is how i am (trying to ) read, (for cerntainly)
ObjectInputStream input = null;
String filename = "testFilemost.srl";
try {
input = new ObjectInputStream(new FileInputStream(new File(new File(getFilesDir(),"")+File.separator+filename)));
} catch (StreamCorruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
Person myPersonObject = (Person) input.readObject();
text(myPersonObject.a,150,150);
} catch (OptionalDataException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
input.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
and for reading :::
if(mousePressed)
{
Person myPersonObject = new Person();
myPersonObject.a=432;
String filename = "testFilemost.srl";
ObjectOutput out = null;
try {
out = new ObjectOutputStream(new FileOutputStream(new File(getFilesDir(),"")+File.separator+filename));
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
out.writeObject(myPersonObject);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
out.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
You don't need to use the 'byte array' approach. There is an easy way to (de)serialize objects.
EDIT: here's the long version of code
Read:
public void read(){
ObjectInputStream input;
String filename = "testFilemost.srl";
try {
input = new ObjectInputStream(new FileInputStream(new File(new File(getFilesDir(),"")+File.separator+filename)));
Person myPersonObject = (Person) input.readObject();
Log.v("serialization","Person a="+myPersonObject.getA());
input.close();
} catch (StreamCorruptedException e) {
e.printStackTrace();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
Write:
public void write(){
Person myPersonObject = new Person();
myPersonObject.setA(432);
String filename = "testFilemost.srl";
ObjectOutput out = null;
try {
out = new ObjectOutputStream(new FileOutputStream(new File(getFilesDir(),"")+File.separator+filename));
out.writeObject(myPersonObject);
out.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
Person class:
public class Person implements Serializable {
private static final long serialVersionUID = -29238982928391L;
int a;
public int getA(){
return a;
}
public void setA(int newA){
a = newA;
}
}
FileNotFoundException when creating a new FileOutputStream means that one of the intermediate directories didn't exist. Try
file.getParentFile().mkdirs();
before creating the FileOutputStream.
Add this code to manifest.xml
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.MANAGE_EXTERNAL_STORAGE"/>
Go to phone setting/applications/your_app/permissions/ allow files and media permission. You can ask permission via by code and when user enter app program will ask permission. If you want I can give you code.
All writen and readen objects must be serializable.(Must implements Serializable interface) If A class extends B class, to set B class serializable is enough.
And add this code to writen and readen class:
private static final long serialVersionUID = 1L;
Write to external memory:
public static void writeToExternal(Serializable object, String filename) {
try {
//File root = new File(Environment.getExternalStorageDirectory(), "MyApp");
//or
File root = new File("/storage/emulated/0/MyApp/");
if (!root.exists()) {
root.mkdirs();
}
File file = new File(root, filename);
FileOutputStream fos = new FileOutputStream(file);
ObjectOutput out = new ObjectOutputStream(fos);
out.writeObject(object);
out.flush();
out.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
If you want to write to internal memory(This memory is not visible and doesn't need permission. This is your app stored in. For this, you can use getFilesDir() instead of getExternalStorageDirectory(). More about https://developer.android.com/reference/android/content/ContextWrapper#getFilesDir%28%29
https://developer.android.com/reference/android/os/Environment.html#getDataDirectory%28%29
https://gist.github.com/granoeste/5574148
https://source.android.com/docs/core/storage
public static void writeToInternal(Context context, Serializable object, String filename){
try {
//File root1 = new File(context.getFilesDir(), "MyApp");
//or
File root = new File("/data/user/0/com.example.myapplication/files/MyApp/");
if (!root.exists()) {
root.mkdirs();
}
File file = new File(root, filename);
FileOutputStream fos = new FileOutputStream(file);
ObjectOutput out = new ObjectOutputStream(fos);
out.writeObject(object);
out.flush();
out.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
Read an object:
public static Object read(String filename) {
try {
File file = new File("/storage/emulated/0/MyApp/" + filename);
FileInputStream fis = new FileInputStream(file);
ObjectInputStream input = new ObjectInputStream(fis);
Object data = (Object) input.readObject();
input.close();
return data;
} catch (StreamCorruptedException e) {
e.printStackTrace();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
return null;
}
When you call read method you must cast to your readen and writen class.(For example Person p = (Person)read("file.txt");
Import all classes and run.

Categories

Resources