How to convert ImageIO.write(input, file, cos) to use in Android - android

Im a getting errors from some code developed in Java that want to use in Android.
ImageIO.write(input, file, cos)
These are my errors for the following code in android, the code works in Java:
BufferedImage cannot be resolved to a type
ImageIO cannot be resolved
public void decryptFile(String key, String typeFile) throws InvalidKeyException,
NoSuchAlgorithmException,
InvalidKeySpecException,
NoSuchPaddingException,
IOException
{
DESKeySpec dks = new DESKeySpec(key.getBytes());
SecretKeyFactory skf = SecretKeyFactory.getInstance("DES");
SecretKey desKey = skf.generateSecret(dks);
Cipher pbeCipher = Cipher.getInstance("DES"); // DES/ECB/PKCS5Padding for SunJCE
pbeCipher.init(Cipher.DECRYPT_MODE, desKey);
// Decrypt the ciphertext and then print it out.
FileInputStream output = null;
File encryptedFile = new File(Environment.getExternalStorageDirectory() + "/images/Et1.jpg");
File decryptedFile = new File(Environment.getExternalStorageDirectory() + "/images/Dt1.jpg");
try
{
output = new FileInputStream(encryptedFile);
}
catch (FileNotFoundException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
CipherInputStream cis = new CipherInputStream(output, pbeCipher);
BufferedImage input = null;
try
{
input = ImageIO.read(cis);
}
catch (IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
FileOutputStream out = null;
try
{
out = new FileOutputStream(decryptedFile);
}
catch (FileNotFoundException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
try
{
ImageIO.write(input,typeFile, out);
}
catch (IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
try
{
cis.close();
}
catch (IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
}

i had similar problems with
import javax.sound.sampled.*;
You need to find the corresponding import (probably ImageIO)
and find a replacement
for me it was
import android.media.AudioFormat;
import android.media.AudioRecord;
import android.media.MediaRecorder;
if thats not the case then post your errors.
Also take in mind it wasnt just a matter of switching the import, i had to port the code to the new library.

Related

CSVReader and android

I want to read in the data from a csv-file and store it into a database. This is how I saved the csv-file (this works without errors - just to show where and how the file is stored which I plan to read with CSVreader):
synchronized public void readFromUrl(String url, String outputFile, Context context) throws FileNotFoundException {
URL downloadLink = null;
try {
downloadLink = new URL(url);
} catch (MalformedURLException e2) {
// TODO Auto-generated catch block
e2.printStackTrace();
}
BufferedReader in = null;
try {
in = new BufferedReader(
new InputStreamReader(downloadLink.openStream(), "UTF8"));
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
FileOutputStream fstream = context.openFileOutput(outputFile,Context.MODE_PRIVATE);
Writer out = new OutputStreamWriter(fstream);
Log.d(TAG, "BufferedReader "+in);
String inputLine = null;
try {
while ((inputLine = in.readLine()) != null){
out.write(inputLine+"\n");
//logger.debug("DOWNLOADED: "+inputLine);
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
fstream.close();
out.close();
in.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
My code so far for reading the csv file:
public void readInCSVFile(String filename, Context context) throws IOException {
IDbHelper dbHelper = new DbHelper(); ;
CSVReader products = null;
products = new CSVReader(new InputStreamReader(context.getAssets().open(filename)));
I get a NoClassDefFoundError exception.
I have the opencsv.jar in the Referenced libraries of my android project.
Thanks in advance for your help.
Is your project in the Eclipse IDE? If yes, then have a look whether the lib (opencsv.jar) is set in the "project properties->Java Build Path->Libraries" and that it is checked in the tab: "Order and Export" too. Under "Order and Export" move the lib to the top of the list.
Then clean and rebuild.
PS: If this does not help, then please provide the complete stacktrace of the error.

Filter log information, BufferedWriter in-file invalid

I have a log package.I want to filter the log.e, and save it to another file. But I find BufferedWriter can not reach the expected effect. Such as the two lines in log file below can not store another file.
E/Vold ( 96): Sleep 2s to make sure that coldboot() events are handled
E/WindowManager( 244): setEventDispatching false
attach code:
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.PrintWriter;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class LogSpider {
/**
* #param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
BufferedReader bufferedReader = null;
try {
bufferedReader = new BufferedReader(new FileReader("C:\\Users\\Administrator\\Desktop\\log.txt"));
String line = "";
try {
while((line = bufferedReader.readLine())!=null)
{
Parseelog(line);
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
finally{
try {
bufferedReader.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
public static void Parseelog(String line)
{
BufferedWriter bufferedWriter = null;
try {
bufferedWriter = new BufferedWriter(new FileWriter("C:\\Users\\Administrator\\Desktop\\logspider2.txt"));
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
//Pattern pattern = Pattern.compile("[\\w[.-]]+\\#[\\w[.-]]{2,}\\.[\\w[.-]]+");
Pattern pattern = Pattern.compile("^E.*");
Matcher matcher = pattern.matcher(line);
while(matcher.find())
{
String string = new String(matcher.group());
string += "\n";
System.out.println(string); //here can print the search results
try {
bufferedWriter.write(string, 0, string.length());
bufferedWriter.flush();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
finally{
try {
bufferedWriter.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
}
The problem with you code was that you where opening the logspider2.txt file every time you want to write the matching line. So it was overwriting all the previous data. To solve the issue you need to open your file in the append mode as follows:
bufferedWriter = new BufferedWriter(
new FileWriter(
"F:\\praful\\androidworkspace_2\\Test\\src\\logspider2.txt",true));
I tried you code and made some modification to make it work. Following is the working code:
/**
* #param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
BufferedReader bufferedReader = null;
try {
bufferedReader = new BufferedReader(new FileReader(
"F:\\praful\\androidworkspace_2\\Test\\src\\logs.txt"));
String line = "";
try {
while ((line = bufferedReader.readLine()) != null) {
Parseelog(line);
}
} catch (IOException e) {
e.printStackTrace();
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} finally {
try {
bufferedReader.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
public static void Parseelog(String line) {
BufferedWriter bufferedWriter = null;
// Pattern pattern =
// Pattern.compile("[\\w[.-]]+\\#[\\w[.-]]{2,}\\.[\\w[.-]]+");
Pattern pattern = Pattern.compile("^E.*");
Matcher matcher = pattern.matcher(line);
try {
bufferedWriter = new BufferedWriter(
new FileWriter(
"F:\\praful\\androidworkspace_2\\Test\\src\\logspider2.txt",true));
while (matcher.find()) {
String string = new String(matcher.group());
string += "\n";
System.out.println(string); // here can print the search results
bufferedWriter.write(string);
}
bufferedWriter.flush();
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
bufferedWriter.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
Please changed the file path to your local paths. Hope it help you..

Reading my Serialized Object from File in Android

This is my first attempt at serializing/deserializing objects on any platform and, to put it mildly, I'm confused.
After implementing Serializable to my game object I output it to a file thus:
public void saveGameState(){
ByteArrayOutputStream bos = new ByteArrayOutputStream();
try {
ObjectOutput out = new ObjectOutputStream(bos);
out.writeObject(theGame);//theGame is an instance of the custom class
//TGame which stores game info.
byte[] buf = bos.toByteArray();
FileOutputStream fos = this.openFileOutput(filename,
Context.MODE_PRIVATE);
fos.write(buf);
fos.close();
} catch(IOException ioe) {
Log.e("serializeObject", "error", ioe);
}
File f =this.getDir(filename, 0);
Log.v("FILE",f.getName());
}
This seems to work, in that I get no exceptions raised. I can only know for sure when I deserialize it. Which is where things go pear shaped.
public God loadSavedGame(){
TGame g=null;
InputStream instream = null;
try {
instream = openFileInput(filename);
} catch (FileNotFoundException e) {
e.printStackTrace();
return null;
}
try {
ObjectInputStream ois = new ObjectInputStream(instream);
try {
g= (TGame) ois.readObject();
return g;
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return null;
}
} catch (StreamCorruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return null;
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return null;
}
}
I got the basis of this code from here Android Java -- Deserializing a file on the Android platform and tried to modify it for my app. When running I get
05-31 23:30:45.493: ERROR/copybit(1279): copyBits failed (Invalid argument)
When the output should be loaded and the saved game start up from when it was saved.
Any help would be appreciated.
The error you've shown is not at all related to serialization: its actually a video display error. I'd suggest looking at the object BEFORE you serialize to make sure its not null, and I'd also suggest serializing to a file on the SD card to make sure you actually had data output (so use new FileOutputStream("/mnt/sdcard/serializationtest") as the output stream and new FileInputStream("/mnt/sdcard/serializationtest") as the input stream) while you are debugging; you can switch back to the context methods after it works, but make sure your sdcard is plugged in while you are doing this.
Finally, modify your logging to look like this:
try {
ObjectInputStream ois = new ObjectInputStream(instream);
try {
g= (TGame) ois.readObject();
return g;
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
android.util.Log.e("DESERIALIZATION FAILED (CLASS NOT FOUND):"+e.getMessage(), e);
e.printStackTrace();
return null;
}
} catch (StreamCorruptedException e) {
android.util.Log.e("DESERIALIZATION FAILED (CORRUPT):"+e.getMessage(), e);
// TODO Auto-generated catch block
e.printStackTrace();
return null;
} catch (IOException e) {
android.util.Log.e("DESERIALIZATION FAILED (IO EXCEPTION):"+e.getMessage(), e);
// TODO Auto-generated catch block
e.printStackTrace();
return null;
}
and see what error gets returned. I expect the serialization is failing somehow.
To seralize or deserialize anything you can use SIMPLE api. It is very easy to use. Download the file and use it in your program
Have a look here
http://simple.sourceforge.net/download/stream/doc/tutorial/tutorial.php#deserialize
Thanks Deepak
I have created below class to do the save and retrieve object.
public class SerializeUtil {
public static <T extends Serializable> void saveObjectToFile(Context context, T object, String fileName){
try {
FileOutputStream fos = context.openFileOutput(fileName, Context.MODE_PRIVATE);
ObjectOutputStream os = new ObjectOutputStream(fos);
os.writeObject(object);
os.close();
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
public static<T extends Serializable> T getObjectFromFile(Context context, String fileName){
T object = null;
try {
FileInputStream fis = context.openFileInput(fileName);
ObjectInputStream is = new ObjectInputStream(fis);
object = (T) is.readObject();
is.close();
fis.close();
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
return object;
}
public static void removeSerializable(Context context, String filename) {
context.deleteFile(filename);
}
}

Creating vCard file programmatically in android

I am using the following code to read contacts and create a vcard file.
String lookupKey = cur.getString(cur.getColumnIndex(Contacts.LOOKUP_KEY));
Uri uri=Uri.withAppendedPath(ContactsContract.Contacts.CONTENT_VCARD_URI, lookupKey);
try {
fd = cr.openAssetFileDescriptor(uri, "r");
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
fis = fd.createInputStream();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
byte[] buf = new byte[(int)fd.getDeclaredLength()];
try {
if (0 < fis.read(buf))
{
vCard = new String(buf);
writer.write(vCard);
writer.write("\n");
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
But while going through the list of contacts, I get the error:
ERROR/MemoryFile(284):
MemoryFile.finalize() called while
ashmem still open.
And my generated .vcf file is missing some contacts and also does not end properly.
Can someone please tell me what is wrong with my code.
You need close stream fis
try {
fis = fd.createInputStream();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
byte[] buf = new byte[(int)fd.getDeclaredLength()];
try {
if (0 < fis.read(buf))
{
vCard = new String(buf);
writer.write(vCard);
writer.write("\n");
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// Close stream
fis.close();
I had the same issue. I used a open source android-vcard jar to write the contacts to vcard.

reading .key file android

I have problem when i try to read a .key file. This file is created by a normal java (J2SE) and i read it from android application. When i read this file from android it gives me nothing and i have done some debugging and i noticed that it can't read the file. Also i have checked if i can read the file (using file.canRead()) and it appears that i can't. Notice that i created normal java application (J2SE) with the same code and it worked successfully.
The code I have used is this:
public KeyPair LoadKeyPair(String algorithm, String publicFileName, String privateFileName) {
// Read Public Key.
PublicKey publicKey = null;
PrivateKey privateKey = null;
try {
File filePublicKey = new File(publicFileName);
FileInputStream fis = new FileInputStream(publicFileName); // The program stops here
byte[] encodedPublicKey = new byte[(int) filePublicKey.length()];
fis.read(encodedPublicKey);
fis.close();
// Read Private Key.
File filePrivateKey = new File(privateFileName);
fis = new FileInputStream(privateFileName);
byte[] encodedPrivateKey = new byte[(int) filePrivateKey.length()];
fis.read(encodedPrivateKey);
fis.close();
// Generate KeyPair.
KeyFactory keyFactory = KeyFactory.getInstance(algorithm);
X509EncodedKeySpec publicKeySpec = new X509EncodedKeySpec(
encodedPublicKey);
publicKey = keyFactory.generatePublic(publicKeySpec);
PKCS8EncodedKeySpec privateKeySpec = new PKCS8EncodedKeySpec(
encodedPrivateKey);
privateKey = keyFactory.generatePrivate(privateKeySpec);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (NoSuchAlgorithmException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InvalidKeySpecException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return new KeyPair(publicKey, privateKey);
}
Is a .key file just like a .pem file?
If so, I just do something like this, because PemReader is in BouncyCastleProvider, and THAT is a mess! Too much code for too few things that I want to use
if(mKey==null){
BufferedReader pubFile = new BufferedReader(new InputStreamReader(mCtx.getResources().openRawResource(R.raw.public.pem)));
try {
String line = new String();
StringBuilder key = new StringBuilder();
while((line = pubFile.readLine())!= null){
if(!line.contains("----")){
key.append(line);
}
}
mKey = key.toString();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
pubFile.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
As you can see, I have my public.pem in the res/raw/ folder within my application. Of course, I dont have a .pem with the private key in it. I sign with my public key and verify that the info was signed with a public key made from the private key I keep on my server.
Hope that answers your question and is clear enough.
Did you add in the Manifest the following line?
<uses-permission android:name="android.permission.READ_INTERNAL_STORAGE"/>

Categories

Resources