I have created a file
inside assests folder and now I want to read the file from a java class and pass it to another function in the same class but for some reason i am unable to use getAssest() method. Please help!
public void configuration()
{
String text = "";
try {
InputStream is = getAssets().open("config.txt");
int size = is.available();
byte[] buffer = new byte[size];
is.read(buffer);
is.close();
text = new String(buffer);
} catch (IOException e) {
e.printStackTrace();
}
}
public IExtraFeeCalculator getExtraFeeCalculator()
{
if(efCalculator==null)
{
if(configuration(Context context) == "extrafeeCalculaotor")
{
String className = System.getProperty("extraFeeCalculator.class.name");
try {
efCalculator = (IExtraFeeCalculator)Class.forName(className).newInstance();
} catch (InstantiationException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
}
return efCalculator;
}
You should try
getResources().getAssets().open("config.txt")
instead of
context.getAssets().open("config.txt");
Change your Method with Single Parameter Context ....
Pass Context from where you Call this Method..
public void configuration(Context context)
{
String text = "";
try {
InputStream is = context.getAssets().open("config.txt");
int size = is.available();
byte[] buffer = new byte[size];
is.read(buffer);
is.close();
text = new String(buffer);
} catch (IOException e) {
e.printStackTrace();
}
}
Yes now as per i think you are not aware from java structure...
Suppose you have this YOUR_CLASS_NAME.java
public void YOUR_CLASS_NAME{
Context context;
YOUR_CLASS_NAME(Context context){
this.context=context;
}
public void configuration(Context context)
{
String text = "";
try {
InputStream is = getAssets().open("config.txt");
int size = is.available();
byte[] buffer = new byte[size];
is.read(buffer);
is.close();
text = new String(buffer);
} catch (IOException e) {
e.printStackTrace();
}
}
public IExtraFeeCalculator getExtraFeeCalculator()
{
if(efCalculator==null)
{
if(configuration(context) == "extrafeeCalculaotor")
{
String className = System.getProperty("extraFeeCalculator.class.name");
try {
efCalculator = (IExtraFeeCalculator)Class.forName(className).newInstance();
} catch (InstantiationException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
}
return efCalculator;
}
}
Use this Code
BufferedReader reader = null;
try {
StringBuilder returnString = new StringBuilder();
reader = new BufferedReader(
new InputStreamReader(getAssets().open("filename.txt")));
String mLine;
while ((mLine = reader.readLine()) != null) {
//process line
returnString.append(mLine );
}
} catch (IOException e) {
//log the exception
} finally {
if (reader != null) {
try {
reader.close();
} catch (IOException e) {
//log the exception
}
}
}
Related
I'm trying to exchange files between two devices using android wifi direct. Any of the device can send and receive files. After discovering and connecting the two devices,I can only successfully send and receive a file/files upon the first time calling send. I'm unable to send any file afterwards. In addition,transfer speed is very slow(it takes about three minutes to transfer a 10mb file)
void startServer(){
String intRoot = new FilesDisplayFragment().internalDirRoot;
ExecutorService serverExecutor = newSingleThreadExecutor();
serverExecutor.submit(new Runnable() {
#Override
public void run() {
ServerSocket serverSocket = null;
try {
serverSocket = new ServerSocket(8888);
} catch (IOException e) {
e.printStackTrace();
}
try {
socket = serverSocket.accept();
} catch (IOException e) {
e.printStackTrace();
}
BufferedInputStream bis = null;
try {
bis = new BufferedInputStream(socket.getInputStream());
} catch (IOException e) {
e.printStackTrace();
}
DataInputStream dis = new DataInputStream(bis);
int filesCount = 0;
try {
filesCount = dis.readInt();
} catch (IOException e) {
e.printStackTrace();
}
File[] files = new File[filesCount];
for(int i = 0; i < filesCount; i++)
{
long fileLength = 0;
try {
fileLength = dis.readLong();
} catch (IOException e) {
e.printStackTrace();
}
String fileType = null;
try {
fileType = dis.readUTF();
} catch (IOException e) {
e.printStackTrace();
}
String fileName = null;
try {
fileName = dis.readUTF();
} catch (IOException e) {
e.printStackTrace();
}
if (fileType == "apk"){
File dirs = new File(intRoot + "RemoteView/" + "app");
if(!dirs.exists()) dirs.mkdirs();
files[i] = new File(dirs.toString() + "/" + fileName);
}
FileOutputStream fos = null;
try {
fos = new FileOutputStream(files[i]);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
BufferedOutputStream bos = new BufferedOutputStream(fos);
for(int j = 0; j < fileLength; j++) {
try {
bos.write(bis.read());
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
});
}
void startClient(Intent intent){
socket = new Socket();
String intRoot = new FilesDisplayFragment().internalDirRoot;
Parcelable parcelable = intent.getParcelableExtra("hostAdd");
Parceler parceler = Parcels.unwrap(parcelable);
String hostAdd = parceler.getGroupOwnerAddress().getHostAddress();
ExecutorService clientExecutor = newSingleThreadExecutor();
clientExecutor.submit(new Runnable() {
#Override
public void run() {
try {
socket.connect(new InetSocketAddress(hostAdd, 8888), 5000);
} catch (IOException e) {
e.printStackTrace();
}
BufferedInputStream bis = null;
try {
bis = new BufferedInputStream(socket.getInputStream());
} catch (IOException e) {
e.printStackTrace();
}
DataInputStream dis = new DataInputStream(bis);
int filesCount = 0;
try {
filesCount = dis.readInt();
} catch (IOException e) {
e.printStackTrace();
}
File[] files = new File[filesCount];
for(int i = 0; i < filesCount; i++)
{
long fileLength = 0;
try {
fileLength = dis.readLong();
} catch (IOException e) {
e.printStackTrace();
}
String fileType = null;
try {
fileType = dis.readUTF();
} catch (IOException e) {
e.printStackTrace();
}
String fileName = null;
try {
fileName = dis.readUTF();
} catch (IOException e) {
e.printStackTrace();
}
if (fileType == "apk"){
File dirs = new File(intRoot + "RemoteView/" + "app");
if(!dirs.exists()) dirs.mkdirs();
files[i] = new File(dirs.toString() + "/" + fileName);
}
FileOutputStream fos = null;
try {
fos = new FileOutputStream(files[i]);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
BufferedOutputStream bos = new BufferedOutputStream(fos);
for(int j = 0; j < fileLength; j++) {
try {
bos.write(bis.read());
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
});
}
void send(Intent intent){
Parcelable parcelable = intent.getParcelableExtra("selected_wifi_files");
Parceler parceler = Parcels.unwrap(parcelable);
File[] files = parceler.getSelectedFilesWifi();
ExecutorService sendExecutor = newSingleThreadExecutor();
sendExecutor.submit(new Runnable() {
#Override
public void run() {
If(bos == null){
BufferedOutputStream bos = null;
try {
bos = new BufferedOutputStream(socket.getOutputStream());
} catch (IOException e) {
e.printStackTrace();
}
DataOutputStream dos = new DataOutputStream(bos);
BufferedOutputStream bos = null;
try {
bos = new BufferedOutputStream(socket.getOutputStream());
} catch (IOException e) {
e.printStackTrace();
}
DataOutputStream dos = new DataOutputStream(bos);
}
try {
dos.writeInt(files.length);
} catch (IOException e) {
e.printStackTrace();
}
for(File file : files)
{
long length = file.length();
try {
dos.writeLong(length);
} catch (IOException e) {
e.printStackTrace();
}
String fileType = FilenameUtils.getExtension(String.valueOf(file));
try {
dos.writeUTF(fileType);
} catch (IOException e) {
e.printStackTrace();
}
String name = file.getName();
try {
dos.writeUTF(name);
} catch (IOException e) {
e.printStackTrace();
}
FileInputStream fis = null;
try {
fis = new FileInputStream(file);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
BufferedInputStream bis = new BufferedInputStream(fis);
int theByte = 0;
while(true) {
try {
if (!((theByte = bis.read()) != -1)) break;
} catch (IOException e) {
e.printStackTrace();
}
try {
bos.write(theByte);
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
});
}
I'm developing a project where client sends screenshots of its activity to server where the bitmap is converted to string.For me it works well.I would like to add a chat between client and server in this project.How can I achieve this?Any kind of help is accepted.
Client Code
public class Client2 extends AsyncTask<Void, Void, Void> {
public static String dstAddress;
int dstPort;
String response= new String() ;
String msg_server=new String();
Context context;
public static ArrayList<Bitmap>ss=new ArrayList<>();
public static Socket socket;
Client2(Context ic,String addr, int port,String msg) {
context=ic;
dstAddress = addr;
dstPort = port;
msg_server=msg;
}
#Override
protected Void doInBackground(Void... arg0) {
socket = null;
ObjectOutputStream dataOutputStream = null;
ObjectInputStream dataInputStream = null;
try {
socket = new Socket(dstAddress, dstPort);
dataOutputStream = new ObjectOutputStream(
socket.getOutputStream());
dataInputStream = new ObjectInputStream(socket.getInputStream());
if(msg_server != null){
dataOutputStream.writeObject(msg_server);
dataOutputStream.flush();
}
response = (String) dataInputStream.readObject();
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
response = "UnknownHostException: " + e.toString();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
response = "IOException: " + e.toString();
} catch (ClassNotFoundException e) {
e.printStackTrace();
} finally {
if (socket != null) {
try { socket.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if (dataOutputStream != null) {
try {
dataOutputStream.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if (dataInputStream != null) {
try {
dataInputStream.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
Toast.makeText(context, response, Toast.LENGTH_SHORT).show();
}}
Server Code
public class Server extends Thread{
ServerSocket serverSocket;
Viewer activity;
static final int SocketServerPORT = 8080;
int count = 0;
int sc=0;
Bitmap bmviewer;
String msgtoclient,msgfromclient;
ArrayList<Bitmap>ser=new ArrayList<>();
public Server(Activity context,String msg )
{
activity= (Viewer) context;
msgtoclient=msg;
}
#Override
public void run() {
Socket socket = null;
ObjectInputStream dataInputStream = null;
ObjectOutputStream dataOutputStream = null;
try {
// serverSocket = new ServerSocket(SocketServerPORT);
serverSocket = new ServerSocket(); // <-- create an unbound socket first
serverSocket.setReuseAddress(true);
serverSocket.bind(new InetSocketAddress(SocketServerPORT));// serverSocket.setReuseAddress(true);
activity.runOnUiThread(new Runnable() {
#Override
public void run() {
Viewer.demo.setText("Port No: "
+ serverSocket.getLocalPort());
}
});
while (true) {
socket = serverSocket.accept();
dataInputStream = new ObjectInputStream(
socket.getInputStream());
dataOutputStream = new ObjectOutputStream(
socket.getOutputStream());
String messageFromClient = new String();
//If no message sent from client, this code will block the program
messageFromClient = (String) dataInputStream.readObject();
count++;
bmviewer = (stringtobitmap(messageFromClient));
activity.runOnUiThread(new Runnable() {
#Override
public void run() {
//Viewer.demo.setText(message);
sc++;
saveimage(bmviewer, sc);
// Viewer.images.setImageBitmap(bmviewer);
Viewer.imageGallery.addView(getImageView(bmviewer));
}
});
if (msgtoclient.equals("")){
String reply="received";
dataOutputStream.writeObject(reply);
dataOutputStream.flush();}
else {
dataOutputStream.writeObject(msgtoclient);
dataOutputStream.flush();
}
}
}catch(EOFException e){
e.printStackTrace();
final String errMsg = e.toString();
activity.runOnUiThread(new Runnable() {
#Override
public void run() {
Snackbar snackbar=Snackbar.make(Viewer.relativeLayout,errMsg,Snackbar.LENGTH_LONG);
snackbar.show();
}
});
} catch(IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
final String errMsg = e.toString();
activity.runOnUiThread(new Runnable() {
#Override
public void run() {
Snackbar snackbar=Snackbar.make(Viewer.relativeLayout,errMsg,Snackbar.LENGTH_LONG);
snackbar.show();
}
});
} catch (ClassNotFoundException e) {
e.printStackTrace();
} finally {
if (socket != null) {
try {
socket.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if (dataInputStream != null) {
try {
dataInputStream.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if (dataOutputStream != null) {
try {
dataOutputStream.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
private View getImageView(Bitmap image) {
ImageView imageView = new ImageView(activity);
LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);
lp.setMargins(0, 0, 10, 0);
imageView.setLayoutParams(lp);
imageView.setImageBitmap(image);
return imageView;
}
private void saveimage(Bitmap bmp,int c) {
sc=c;
String root = Environment.getExternalStorageDirectory().toString();
File myDir = new File(root + "/screenshare_viewer");
myDir.mkdirs();
//Random generator = new Random();
// int n = 10000;
// n = generator.nextInt(n);
String fname = "Image-"+sc +".jpg";
File file = new File (myDir, fname);
if (file.exists ()) file.delete ();
try {
FileOutputStream out = new FileOutputStream(file);
bmp.compress(Bitmap.CompressFormat.JPEG, 90, out);
out.flush();
out.close();
} catch (Exception e) {
e.printStackTrace();
}
}
private Bitmap stringtobitmap(String message) {
try{
byte [] encodeByte= Base64.decode(message,Base64.DEFAULT);
Bitmap bitmap= BitmapFactory.decodeByteArray(encodeByte, 0, encodeByte.length);
return bitmap;
}
catch(Exception e){
e.getMessage();
return null;
}
}
}
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();
}
}
}
I have succesfully saved int values to sd but cant read. It always gives numberformat information. I made all logics, but cant find why it gives error.
Here is my code ;
this my constant
private final static String EXTERNAL_FILES_DIR = "ARDROID";
private final static String FILE_NAME = "turkcell.txt";
private boolean isThereAnySavedFile = false;
when this method called, it tries to open file, if file does not exist, create the file
public void anySavedDataInSD() {
String textFromSD = String.valueOf(read());
if (isThereAnySavedFile) {
int numberOfSendedSMS = Integer.parseInt(textFromSD.toString());
numberOfSendedSMS++;
writeToSD(String.valueOf(numberOfSendedSMS));
} else {
int first=60;
String g = String.valueOf(first);
writeToSD(g);
}
}
this method for writing
private void write(File file, String msg) {
FileOutputStream outputStream = null;
try {
outputStream = new FileOutputStream(file);
outputStream.write(msg.getBytes());
Logger.info("oldu bu kez");
} catch (IOException e) {
Logger.info("oldu bu kez2" + e);
} finally {
Logger.info("oldu bu kez3");
try {
if (outputStream != null)
outputStream.close();
} catch (IOException exception) {
}
}
}
this methof for reading
public StringBuilder read() {
StringBuilder textBuilder = new StringBuilder();
BufferedReader reader = null;
try {
File externalFilesDir = getExternalFilesDir(EXTERNAL_FILES_DIR);
File file = new File(externalFilesDir, FILE_NAME);
Logger.info("oldu2");
reader = new BufferedReader(new FileReader(file));
String line;
while ((line = reader.readLine()) != null) {
textBuilder.append(line);
textBuilder.append("\n");
}
isThereAnySavedFile = true;
} catch (FileNotFoundException e) {
Logger.info("oldu3");
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (reader != null) {
try {
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return textBuilder;
}
I'm looking for a kind of Serialization for the java.security.KeyPair to store and read from the Shared Preferences.
Storing the .toString() is now quite sinful cause there is no Constructor for the KeyPair.
Suggestions?
I'm afraid there is no way of storing a Serializable object in SharedPreferences. I recommend looking into saving it as a private file, see Android Storage Options, FileOutputStream and ObjectOutputStream for more information.
public static void write(Context context, Object obj, String filename) {
ObjectOutputStream oos = null;
try {
FileOutputStream file = context.openFileOutput(filename, Activity.MODE_PRIVATE);
oos = new ObjectOutputStream(file);
oos.writeObject(obj);
} catch (IOException e) {
e.printStackTrace();
} finally {
if (oos != null) {
try {
oos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
public static Object read(Context context, String filename) {
ObjectInputStream ois = null;
Object obj = null;
try {
FileInputStream file = context.getApplicationContext().openFileInput(filename);
ois = new ObjectInputStream(file);
obj = ois.readObject();
} catch (FileNotFoundException e) {
// Just let it return null.
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
} finally {
if (ois != null) {
try {
ois.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return obj;
}
I actually solved in it this way:
I first create a String by using Base64, which I store and then recreate from the Shared Proferences:
SharedPreferences prefs = this.getSharedPreferences(
PATH, Context.MODE_PRIVATE);
String key = prefs.getString(KEYPATH, "");
if (key.equals("")) {
// generate KeyPair
KeyPair kp = Encrypter.generateKeyPair();
ByteArrayOutputStream b = new ByteArrayOutputStream();
ObjectOutputStream o;
try {
o = new ObjectOutputStream(b);
o.writeObject(kp);
} catch (IOException e) {
e.printStackTrace();
}
byte[] res = b.toByteArray();
String encodedKey = Base64.encodeToString(res, Base64.DEFAULT);
prefs.edit().putString(KEYPATH, encodedKey).commit();
} else {
// read the KeyPair from internal storage
byte[] res = Base64.decode(key, Base64.DEFAULT);
ByteArrayInputStream bi = new ByteArrayInputStream(res);
ObjectInputStream oi;
try {
oi = new ObjectInputStream(bi);
Object obj = oi.readObject();
Encrypter.setMyKeyPair((KeyPair) obj);
Log.w(TAG, ((KeyPair) obj).toString());
} catch (StreamCorruptedException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}