Read and write a file with file chooser Android - java

i'm wiritng an app with Android Studio, I've setted a file chooser that give me the path of a file (the file could be on external or internal storage). I need read the chosen file, modify it and write in the same position with another name. I've implemented read and write function but they don't work with separator because they use FileInputStream/FileOutputStream, i've tried already a function with FileReader but return null. Someone how resolve my problem?
Thanks in Advance!
My read/write function:
public String Read_file(String fn, Context context) {
int ch;
String d;
StringBuffer fileContent = new StringBuffer("");
FileInputStream fis;
try {
fis = context.openFileInput(fn);
try {
while( (ch = fis.read()) != -1)
fileContent.append((char)ch);
} catch (IOException e) {
e.printStackTrace();
}
} catch (FileNotFoundException e) {
e.printStackTrace();
System.out.println("Error");
}
return d = new String(fileContent);
}
public void Write_file(String fn, String data, Context context){
FileOutputStream outS;
//Scrive sul file
try {
outS = context.openFileOutput(fn, Context.MODE_PRIVATE);
outS.write(data.getBytes());
outS.close();
} catch (Exception e) {
e.printStackTrace();
}
}
I've already tried this but return null:
public String t(String fname){
BufferedReader br = null;
String response = null;
try {
StringBuffer output = new StringBuffer();
//String fpath = "/sdcard/"+fname+".txt";
br = new BufferedReader(new FileReader(fname));
String line = "";
while ((line = br.readLine()) != null) {
output.append(line +"n");
}
response = output.toString();
} catch (IOException e) {
e.printStackTrace();
return null;
}
return response;
}
My choose file:
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
if(requestCode == 10){
if(resultCode == RESULT_OK){
Uri uri = data.getData();
String src = uri.getPath();
String file_name = uri.getLastPathSegment();
String fn = src.substring(src.lastIndexOf('/') + 1);
System.out.println(fn);
//////READ THE FILE AT THE URI
}
}
}

Had a similar issue tring to open the file using fileName.getPath()
Kept getting file not found and all the content:path information was lost.
looking into content providers highlighted FileDescriptors.
Opening a fileDescriptor resulted in a ParcelFileDescriptor in which you can get the fileDescriptor and then onto opening a FileReader or an FileInputStream depending on your use case.
fun readFile(fileName: Uri): String? {
val fileDescriptor = requireContext().contentResolver.openFileDescriptor(fileName, "r") ?: return null
val fReader = FileReader(fileDescriptor.fileDescriptor)
//val file = File(fileName.path)
var bufferedReader: BufferedReader? = null
try {
bufferedReader = BufferedReader(fReader)
val stringBuilder = StringBuilder()
var line: String?
while (bufferedReader.readLine().also { line = it } != null) {
stringBuilder.append(line)
stringBuilder.append(System.lineSeparator())
}
return stringBuilder.toString()
} catch (e: FileNotFoundException) {
System.err.println("File : Not found")
e.printStackTrace()
} catch (e: IOException) {
e.printStackTrace()
} finally {
try {
bufferedReader?.close()
fReader.close()
fileDescriptor.close()
} catch (e: IOException) {
e.printStackTrace()
}
}
return null
}

Related

Write and load from a file in Android [duplicate]

I want to save a file to the internal storage by getting the text inputted from EditText. Then I want the same file to return the inputted text in String form and save it to another String which is to be used later.
Here's the code:
package com.omm.easybalancerecharge;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.telephony.TelephonyManager;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final EditText num = (EditText) findViewById(R.id.sNum);
Button ch = (Button) findViewById(R.id.rButton);
TelephonyManager operator = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
String opname = operator.getNetworkOperatorName();
TextView status = (TextView) findViewById(R.id.setStatus);
final EditText ID = (EditText) findViewById(R.id.IQID);
Button save = (Button) findViewById(R.id.sButton);
final String myID = ""; //When Reading The File Back, I Need To Store It In This String For Later Use
save.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
//Get Text From EditText "ID" And Save It To Internal Memory
}
});
if (opname.contentEquals("zain SA")) {
status.setText("Your Network Is: " + opname);
} else {
status.setText("No Network");
}
ch.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
//Read From The Saved File Here And Append It To String "myID"
String hash = Uri.encode("#");
Intent intent = new Intent(Intent.ACTION_CALL);
intent.setData(Uri.parse("tel:*141*" + /*Use The String With Data Retrieved Here*/ num.getText()
+ hash));
startActivity(intent);
}
});
}
I have included comments to help you further analyze my points as to where I want the operations to be done/variables to be used.
Hope this might be useful to you.
Write File:
private void writeToFile(String data,Context context) {
try {
OutputStreamWriter outputStreamWriter = new OutputStreamWriter(context.openFileOutput("config.txt", Context.MODE_PRIVATE));
outputStreamWriter.write(data);
outputStreamWriter.close();
}
catch (IOException e) {
Log.e("Exception", "File write failed: " + e.toString());
}
}
Read File:
private String readFromFile(Context context) {
String ret = "";
try {
InputStream inputStream = context.openFileInput("config.txt");
if ( inputStream != null ) {
InputStreamReader inputStreamReader = new InputStreamReader(inputStream);
BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
String receiveString = "";
StringBuilder stringBuilder = new StringBuilder();
while ( (receiveString = bufferedReader.readLine()) != null ) {
stringBuilder.append("\n").append(receiveString);
}
inputStream.close();
ret = stringBuilder.toString();
}
}
catch (FileNotFoundException e) {
Log.e("login activity", "File not found: " + e.toString());
} catch (IOException e) {
Log.e("login activity", "Can not read file: " + e.toString());
}
return ret;
}
For those looking for a general strategy for reading and writing a string to file:
First, get a file object
You'll need the storage path. For the internal storage, use:
File path = context.getFilesDir();
For the external storage (SD card), use:
File path = context.getExternalFilesDir(null);
Then create your file object:
File file = new File(path, "my-file-name.txt");
Write a string to the file
FileOutputStream stream = new FileOutputStream(file);
try {
stream.write("text-to-write".getBytes());
} finally {
stream.close();
}
Or with Google Guava
String contents = Files.toString(file, StandardCharsets.UTF_8);
Read the file to a string
int length = (int) file.length();
byte[] bytes = new byte[length];
FileInputStream in = new FileInputStream(file);
try {
in.read(bytes);
} finally {
in.close();
}
String contents = new String(bytes);
Or if you are using Google Guava
String contents = Files.toString(file,"UTF-8");
For completeness I'll mention
String contents = new Scanner(file).useDelimiter("\\A").next();
which requires no libraries, but benchmarks 50% - 400% slower than the other options (in various tests on my Nexus 5).
Notes
For each of these strategies, you'll be asked to catch an IOException.
The default character encoding on Android is UTF-8.
If you are using external storage, you'll need to add to your manifest either:
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
or
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
Write permission implies read permission, so you don't need both.
public static void writeStringAsFile(final String fileContents, String fileName) {
Context context = App.instance.getApplicationContext();
try {
FileWriter out = new FileWriter(new File(context.getFilesDir(), fileName));
out.write(fileContents);
out.close();
} catch (IOException e) {
Logger.logError(TAG, e);
}
}
public static String readFileAsString(String fileName) {
Context context = App.instance.getApplicationContext();
StringBuilder stringBuilder = new StringBuilder();
String line;
BufferedReader in = null;
try {
in = new BufferedReader(new FileReader(new File(context.getFilesDir(), fileName)));
while ((line = in.readLine()) != null) stringBuilder.append(line);
} catch (FileNotFoundException e) {
Logger.logError(TAG, e);
} catch (IOException e) {
Logger.logError(TAG, e);
}
return stringBuilder.toString();
}
Just a a bit modifications on reading string from a file method for more performance
private String readFromFile(Context context, String fileName) {
if (context == null) {
return null;
}
String ret = "";
try {
InputStream inputStream = context.openFileInput(fileName);
if ( inputStream != null ) {
InputStreamReader inputStreamReader = new InputStreamReader(inputStream);
int size = inputStream.available();
char[] buffer = new char[size];
inputStreamReader.read(buffer);
inputStream.close();
ret = new String(buffer);
}
}catch (Exception e) {
e.printStackTrace();
}
return ret;
}
The Kotlin way by using builtin Extension function on File
Write: yourFile.writeText(textFromEditText)
Read: yourFile.readText()
check the below code.
Reading from a file in the filesystem.
FileInputStream fis = null;
try {
fis = context.openFileInput(fileName);
InputStreamReader isr = new InputStreamReader(fis);
// READ STRING OF UNKNOWN LENGTH
StringBuilder sb = new StringBuilder();
char[] inputBuffer = new char[2048];
int l;
// FILL BUFFER WITH DATA
while ((l = isr.read(inputBuffer)) != -1) {
sb.append(inputBuffer, 0, l);
}
// CONVERT BYTES TO STRING
String readString = sb.toString();
fis.close();
catch (Exception e) {
} finally {
if (fis != null) {
fis = null;
}
}
below code is to write the file in to internal filesystem.
FileOutputStream fos = null;
try {
fos = context.openFileOutput(fileName, Context.MODE_PRIVATE);
fos.write(stringdatatobestoredinfile.getBytes());
fos.flush();
fos.close();
} catch (Exception e) {
} finally {
if (fos != null) {
fos = null;
}
}
I think this will help you.
I'm a bit of a beginner and struggled getting this to work today.
Below is the class that I ended up with. It works but I was wondering how imperfect my solution is. Anyway, I was hoping some of you more experienced folk might be willing to have a look at my IO class and give me some tips. Cheers!
public class HighScore {
File data = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + File.separator);
File file = new File(data, "highscore.txt");
private int highScore = 0;
public int readHighScore() {
try {
BufferedReader br = new BufferedReader(new FileReader(file));
try {
highScore = Integer.parseInt(br.readLine());
br.close();
} catch (NumberFormatException | IOException e) {
e.printStackTrace();
}
} catch (FileNotFoundException e) {
try {
file.createNewFile();
} catch (IOException ioe) {
ioe.printStackTrace();
}
e.printStackTrace();
}
return highScore;
}
public void writeHighScore(int highestScore) {
try {
BufferedWriter bw = new BufferedWriter(new FileWriter(file));
bw.write(String.valueOf(highestScore));
bw.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
Kotlin
class FileReadWriteService {
private var context:Context? = ContextHolder.instance.appContext
fun writeFileOnInternalStorage(fileKey: String, sBody: String) {
val file = File(context?.filesDir, "files")
try {
if (!file.exists()) {
file.mkdir()
}
val fileToWrite = File(file, fileKey)
val writer = FileWriter(fileToWrite)
writer.append(sBody)
writer.flush()
writer.close()
} catch (e: Exception) {
Logger.e(classTag, e)
}
}
fun readFileOnInternalStorage(fileKey: String): String {
val file = File(context?.filesDir, "files")
var ret = ""
try {
if (!file.exists()) {
return ret
}
val fileToRead = File(file, fileKey)
val reader = FileReader(fileToRead)
ret = reader.readText()
reader.close()
} catch (e: Exception) {
Logger.e(classTag, e)
}
return ret
}
}
the first thing we need is the permissions in AndroidManifest.xml
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
so in an asyncTask Kotlin class, we treat the creation of the file
import android.os.AsyncTask
import android.os.Environment
import android.util.Log
import java.io.*
class WriteFile: AsyncTask<String, Int, String>() {
private val mFolder = "/MainFolder"
lateinit var folder: File
internal var writeThis = "string to cacheApp.txt"
internal var cacheApptxt = "cacheApp.txt"
override fun doInBackground(vararg writethis: String): String? {
val received = writethis[0]
if(received.isNotEmpty()){
writeThis = received
}
folder = File(Environment.getExternalStorageDirectory(),"$mFolder/")
if(!folder.exists()){
folder.mkdir()
val readME = File(folder, cacheApptxt)
val file = File(readME.path)
val out: BufferedWriter
try {
out = BufferedWriter(FileWriter(file, true), 1024)
out.write(writeThis)
out.newLine()
out.close()
Log.d("Output_Success", folder.path)
} catch (e: Exception) {
Log.d("Output_Exception", "$e")
}
}
return folder.path
}
override fun onPostExecute(result: String) {
super.onPostExecute(result)
if(result.isNotEmpty()){
//implement an interface or do something
Log.d("onPostExecuteSuccess", result)
}else{
Log.d("onPostExecuteFailure", result)
}
}
}
Of course if you are using Android above Api 23, you must handle the request to allow writing to device memory. Something like this
import android.Manifest
import android.content.Context
import android.content.pm.PackageManager
import android.os.Build
import androidx.appcompat.app.AppCompatActivity
import androidx.core.app.ActivityCompat
import androidx.core.content.ContextCompat
class ReadandWrite {
private val mREAD = 9
private val mWRITE = 10
private var readAndWrite: Boolean = false
fun readAndwriteStorage(ctx: Context, atividade: AppCompatActivity): Boolean {
if (Build.VERSION.SDK_INT < 23) {
readAndWrite = true
} else {
val mRead = ContextCompat.checkSelfPermission(ctx, Manifest.permission.READ_EXTERNAL_STORAGE)
val mWrite = ContextCompat.checkSelfPermission(ctx, Manifest.permission.WRITE_EXTERNAL_STORAGE)
if (mRead != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(atividade, arrayOf(Manifest.permission.READ_EXTERNAL_STORAGE), mREAD)
} else {
readAndWrite = true
}
if (mWrite != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(atividade, arrayOf(Manifest.permission.WRITE_EXTERNAL_STORAGE), mWRITE)
} else {
readAndWrite = true
}
}
return readAndWrite
}
}
then in an activity, execute the call.
var pathToFileCreated = ""
val anRW = ReadandWrite().readAndwriteStorage(this,this)
if(anRW){
pathToFileCreated = WriteFile().execute("onTaskComplete").get()
Log.d("pathToFileCreated",pathToFileCreated)
}
We can use this code to write String to a file
public static void writeTextToFile(final String filename, final String data) {
File file = new File(filename);
try {
FileOutputStream stream = new FileOutputStream(file);
stream.write(data.getBytes());
stream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
Then in the Main code, we use this, for example
writeTextToFile(getExternalFilesDir("/").getAbsolutePath() + "/output.txt", "my-example-text");
After that, check the file at Android/data/<package-name>/files.
The easiest way to append to a text file in kotlin:
val directory = File(context.filesDir, "LogsToSendToNextMunich").apply {
mkdirs()
}
val file = File(directory,"Logs.txt")
file.appendText("You new text")
If you want to just write to the file:
yourFile.writeText("You new text")
writing anything to the files, using bytes:
FileOutputStream(file).use {
it.write("Some text for example".encodeToByteArray())
}

Copy file from path to Path in Android 11

I hope you are fine.
After I have done all steps, of getting permission storage in Android 11, now I can create, copy files from assets to any folder, or delete files.
I just got a problem when try to copy file from path to path, the problem is I find the output file empty.
Only in this I need help, and I hope you help me and tell me what mistake I have in my code, and thanks in advance.
To copy I'm using:
Uri muri = Uri.parse("content://com.android.externalstorage.documents/tree/primary%3Aagora%2file.txt");
Uri uri2 = Uri.parse("content://com.android.externalstorage.documents/tree/primary%3AAlarms");
DocumentFile mfile = DocumentFile.fromTreeUri(MainActivity.this, muri);
DocumentFile mfile1 = DocumentFile.fromTreeUri(MainActivity.this, uri2);
mfile1 = mfile1.createFile("file/txt", "file.txt");
uri2 = mfile1.getUri();
if (copyFileFromUri2(MainActivity.this, muri, uri2)) {
showMessage("file copied successfully");
} else {
showMessage("failed to copy the file !");
}
The method:
public boolean copyFileFromUri2(Context context, Uri fileUri, Uri targetUri)
{
InputStream fis = null;
OutputStream fos = null;
try {
ContentResolver content = context.getContentResolver();
fis = content.openInputStream(fileUri);
fos = content.openOutputStream(targetUri);
byte[] buff = new byte[1024];
int length = 0;
while ((length = fis.read(buff)) > 0) {
fos.write(buff, 0, length);
}
} catch (IOException e) {
return false;
} finally {
if (fis != null) {
try {
fis.close();
} catch (IOException e) {
return false;
}
}
if (fos != null) {
try {
fos.close();
} catch (IOException e) {
return false;
}
}
}
return true;
}
You can try to initialize the OutputStream os as follows:
fos = new BufferedOutputStream( content.openOutputStream(targetUri))

How to Save "Data.Json" file from assets to internal Storage and then use it for read/write

Currently i am fetching a package details(Onnet Minutes, Offnet Minutes, etc) from a Json file "Data.json" from assets but i know we cannot change values from assets. So my Question is how to copy Data.json to internal storage and then Load it for read/Write.
I am using this to load Data.Json from Assets
public String loadJSONFromAsset() {
String json = null;
try {
InputStream is = getAssets().open("Data.json");
int size = is.available();
byte[] buffer = new byte[size];
is.read(buffer);
is.close();
json = new String(buffer, "UTF-8");
Toast.makeText(jazz_sim_lagao_offer_details.this, "JSON Loaded", Toast.LENGTH_SHORT).show();
} catch (IOException ex) {
ex.printStackTrace();
return null;
}
return json;
}
and using this code to update data
private void UpdateData() {
JSONObject JSONobj = null;
try {
loadJSONFromAsset();
//get JSONObject from JSON file
JSONobj = new JSONObject(loadJSONFromAsset());
//fetch JSONObject named
JSONObject Jazz_SimLagaoOffer = JSONobj.getJSONObject("packages").getJSONObject("jazz_packages").getJSONObject("call_packages").getJSONObject("sim_lagao_offer");
String Jazz_SimLagaoOffer_ONNET = Jazz_SimLagaoOffer.getString("onnet");
Jazz_SimLagaoOffer_OnNet_TextView.setText(Jazz_SimLagaoOffer_ONNET);
String Jazz_SimLagaoOffer_OFFNET = Jazz_SimLagaoOffer.getString("offnet");
Jazz_SimLagaoOffer_OffNet_TextView.setText(Jazz_SimLagaoOffer_OFFNET);
String Jazz_SimLagaoOffer_MBs = Jazz_SimLagaoOffer.getString("mbs");
Jazz_SimLagaoOffer_Mb_TextView.setText(Jazz_SimLagaoOffer_MBs);
String Jazz_SimLagaoOffer_SMS = Jazz_SimLagaoOffer.getString("sms");
Jazz_SimLagaoOffer_Sms_TextView.setText(Jazz_SimLagaoOffer_SMS);
String Jazz_SimLagaoOffer_SUBCODE = Jazz_SimLagaoOffer.getString("sub_code");
Jazz_SimLagaoOffer_Sub_Code_TextView.setText(Jazz_SimLagaoOffer_SUBCODE);
String Jazz_SimLagaoOffer_CHECKCODE = Jazz_SimLagaoOffer.getString("check_code");
Jazz_SimLagaoOffer_Check_Code_TextView.setText(Jazz_SimLagaoOffer_CHECKCODE);
String Jazz_SimLagaoOffer_UNSUBCODE = Jazz_SimLagaoOffer.getString("unsub_code");
Jazz_SimLagaoOffer_Unsub_Code_TextView.setText(Jazz_SimLagaoOffer_UNSUBCODE);
Jazz_SimLagaoOffer_Charges = Jazz_SimLagaoOffer.getString("charges");
} catch (JSONException e) {
e.printStackTrace();
Toast.makeText(getBaseContext(), JSONobj + "", Toast.LENGTH_SHORT).show();
}
}
How to Get Json Object?
Here is My Data.Json
{
"packages" : {
"jazz_packages" : {
"call_packages" : {
"sim_lagao_offer" : {
"charges" : "0.01",
"check_code" : "*551*2#",
"mbs" : "1500",
"offnet" : "5000",
"onnet" : "3000",
"sms" : "3000",
"sub_code" : "*551#",
"unsub_code" : "*551*3#"
}
}
}
}
}
Try this
private void CopyAssets() {
AssetManager assetManager = getAssets();
String[] files = null;
System.out.println("File name => "+filename);
InputStream in = null;
OutputStream out = null;
try {
in = assetManager.open(YOUR_ASSETS_FILE); // if files resides inside the "Files" directory itself
out = new FileOutputStream(STORAGE_PATH).toString() +"/" + filename);
copyFile(in, out);
in.close();
in = null;
out.flush();
out.close();
out = null;
} catch(Exception e) {
e.printStackTrace();
}
}
private void copyFile(InputStream in, OutputStream out) throws IOException {
byte[] buffer = new byte[1024];
int read;
while((read = in.read(buffer)) != -1){
out.write(buffer, 0, read);
}
}
Use below code to read from storage
String jsongString = readFromFile();
JSONObject mainJsonObject = new JSONObject(jsongString);
JSONObject Jazz_SimLagaoOffer = mainJsonObject.getJSONObject("packages").getJSONObject("jazz_packages").getJSONObject("call_packages").getJSONObject("sim_lagao_offer");
Use below method to read data from internal storage file and return as String.
private String readFromFile() {
String ret = "";
InputStream inputStream = null;
try {
inputStream = openFileInput("names.json");
if ( inputStream != null ) {
InputStreamReader inputStreamReader = new InputStreamReader(inputStream);
BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
String receiveString = "";
StringBuilder stringBuilder = new StringBuilder();
while ( (receiveString = bufferedReader.readLine()) != null ) {
stringBuilder.append(receiveString);
}
ret = stringBuilder.toString();
}
}
catch (FileNotFoundException e) {
Log.e("login activity", "File not found: " + e.toString());
} catch (IOException e) {
Log.e("login activity", "Can not read file: " + e.toString());
}
finally {
try {
inputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return ret;
}
Hope this work :)
I Got Answer my own Question after 1 Day Research and Thanks to #pratik vekariya
helped me a lot.
CopyAssets() works perfect as defined #pratik vekariya in his answer and to readfromfile see my Question loadJSONFromAssets()
and i Just replaced line
InputStream is = getAssets().open("Data.json");
with this
InputStream is = new FileInputStream(getFilesDir().toString() +"/" + "Data.json");
to to load .json file from files and get json object from inputStrem

How can I run executable in assets?

How can I add a executable into assets and run it in Android and show the output?
I've a executable that will work. I assume there will need to be some chmod in the code.
Thank you.
here is my answer
put copyAssets() to your mainactivity.
someone's code:
private void copyAssets() {
AssetManager assetManager = getAssets();
String[] files = null;
try {
files = assetManager.list("");
} catch (IOException e) {
Log.e("tag", "Failed to get asset file list.", e);
}
for(String filename : files) {
InputStream in = null;
OutputStream out = null;
try {
in = assetManager.open(filename);
File outFile = new File(getFilesDir(), filename);
out = new FileOutputStream(outFile);
copyFile(in, out);
} catch(IOException e) {
Log.e("tag", "Failed to copy asset file: " + filename, e);
}
finally {
if (in != null) {
try {
in.close();
} catch (IOException e) {
// NOOP
}
}
if (out != null) {
try {
out.close();
} catch (IOException e) {
// NOOP
}
}
}
}
}
private void copyFile(InputStream in, OutputStream out) throws IOException {
byte[] buffer = new byte[1024];
int read;
while ((read = in.read(buffer)) != -1) {
out.write(buffer, 0, read);
}
}
also here is code to run command
public String runcmd(String cmd){
try {
Process p = Runtime.getRuntime().exec(cmd);
BufferedReader in = new BufferedReader(new InputStreamReader(p.getInputStream()));
int read;
char[] buffer = new char[4096];
StringBuffer out = new StringBuffer();
while ((read = in.read(buffer)) > 0) {
out.append(buffer, 0, read);
}
in.close();
p.waitFor();
return out.substring(0);
} catch (IOException e) {
throw new RuntimeException(e);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
}
you may need to change it to
String prog= "programname";
String[] env= { "parameter 1","p2"};
File dir= new File(getFilesDir().getAbsolutePath());
Process p = Runtime.getRuntime().exec(prog,env,dir);
to ensure proper parameter handling
also add this to your main code
to check proper copying of files
String s;
File file4 = new File(getFilesDir().getAbsolutePath()+"/executable");
file4.setExecutable(true);
s+=file4.getName();
s+=file4.exists();
s+=file4.canExecute();
s+=file4.length();
//output s however you want it
should write: filename, true, true, correct filelength.
Place your executable in raw folder, then run it by using ProcessBuilder or Runtime.exec like they do here http://gimite.net/en/index.php?Run%20native%20executable%20in%20Android%20App

Fileinput stream / loading a simple txt file

Does anyone know why this crashes? All I'm doing is reading in a file in a txt file from my raw folder and when I click the load button in the other activity window, the code breaks when I call the variable testing within the file reader object upon click. log.d(null, ReadFileObject.fileText) Thanks in advance!
public class ReadFile extends Activity{
public String test;
public String testing;
protected void onCreate(Bundle savedInstanceState) {
}
public void fileText() {
InputStream fis;
fis = getResources().openRawResource(R.raw.checkit);
byte[] input;
try {
input = new byte [fis.available()];
while(fis.read() != -1)
{
test += new String (input);
}
testing = test;
fis.close();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
System.out.println(e.getMessage());
}catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
System.out.println(e.getMessage());
}
/* InputStream fis = null;
try {
fis = getResources().openRawResource(R.raw.checkit);
BufferedReader br = new BufferedReader(new InputStreamReader(fis));
String nextLine;
int i = 0, j = 0;
while ((nextLine = br.readLine()) != null) {
if (j == 5) {
j = 0;
i++;
}
test += nextLine;
}
} catch (Exception e) {
e.printStackTrace();
System.out.println(e.getMessage());
} finally {
if (fis != null) {
try { fis.close(); }
catch (IOException ignored) {}
}
}*/
}
}
Your code is broken here:
byte[] input;
input = new byte [fis.available()];
while(fis.read() != -1) {
test += new String (input);
}
testing = test;
fis.close();
In Java available() is unreliable (read the Javadoc).... and may even return 0. You should instead use a loop similar to:
InputStream fis = getResources().openRawResource(R.raw.checkit);
try {
byte[] buffer = new byte[4096]; // 4K buffer
int len = 0;
while((len = fis.read(buffer)) != -1) {
test += new String (buffer, 0, len);
}
testing = test;
} catch (IOException ioe) {
ioe.printStackTrace();
// make sure you do any other appropriate handling.
} finally {
fis.close();
}
(although using string concatenation is probably not the best idea, use a StringBuilder).
Your class extends `activity but theres nothing inside oncreate. If you need a simple java program try to create New java Project . Since you extend activity you should setcontentview(yourLayout). Then call your method from oncreate and do your stuffs

Categories

Resources