IO Exception in FileInputStream.read. Android - android

I'm writting an Android's app. Two activities, one has TextEdit to type 'hello message', and button to save message in Internal Storage. Second is main activity. Hello mesage should appear after app's start.
Second activity:
String s = ((EditText) findViewById(R.id.message_act_editText_hello)).getText().toString();
FileOutputStream fos = openFileOutput(Lab2AndroidActivity.FILENAME, Context.MODE_PRIVATE);
fos.write(s.getBytes());
fos.close();
first (main) activity:
static String FILENAME = "message_file.zip";
FileOutputStream fos;
try {
//piece of code to guarantee that file exists
fos = openFileOutput(Lab2AndroidActivity.FILENAME, Context.MODE_APPEND);
fos.close();
} catch (FileNotFoundException e1) {
e1.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
fis = openFileInput(FILENAME);
messageString = new StringBuffer("");
while ((length = fis.read(buffer)) != -1) {
String temp = new String(buffer, 0,length);
messageString.append(temp);
fis.close();
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
Toast t = Toast.makeText(this, messageString, 3000);
t.show();
I'm getting IO Exception in logcat at line:
while ((length = fis.read(buffer)) != -1)
but app seems to work correctly (defined message appears after app's start). I tried to find explanation, I found several topics, but all was according to large files, or files in assets, or compressed files.
I tried to name my file like
static String FILENAME = "message_file.zip",
static String FILENAME = "message_file.txt",
to try different extensions, but always i'm getting the same IO Exception.
Thanks for suggestions.

of course you will get an IO Exception your file doesn't exit and you request to open it
You forget this peice of code
File myFile = new File("/sdcard/mysdfile.txt");
In your first activity you can use this code
public class MainActivity extends Activity {
/** Called when the activity is first created. */
EditText txtData;
Button btnWriteSDFile;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
// bind GUI elements with local controls
txtData = (EditText) findViewById(R.id.txtData);
txtData.setHint("Enter some lines of data here...");
btnWriteSDFile = (Button) findViewById(R.id.btnWriteSDFile);
btnWriteSDFile.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
// write on SD card file data in the text box
try {
File myFile = new File("/sdcard/mysdfile.txt");
myFile.createNewFile();
FileOutputStream fOut = new FileOutputStream(myFile);
OutputStreamWriter myOutWriter =
new OutputStreamWriter(fOut);
myOutWriter.append(txtData.getText());
myOutWriter.close();
fOut.close();
Toast.makeText(getBaseContext(),
"Done writing SD 'mysdfile.txt'",
Toast.LENGTH_SHORT).show();
Intent i = new Intent(getApplicationContext(),SecondActivity.class);
startActivity(i);
} catch (Exception e) {
Toast.makeText(getBaseContext(), e.getMessage(),
Toast.LENGTH_SHORT).show();
}
}// onClick
});
}
}
in the second one you can use this:
public class SecondActivity extends Activity {
private TextView txtData2;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main2);
txtData2 = (TextView) findViewById(R.id.textView2);
try {
File myFile = new File("/sdcard/mysdfile.txt");
FileInputStream fIn = new FileInputStream(myFile);
BufferedReader myReader = new BufferedReader(
new InputStreamReader(fIn));
String aDataRow = "";
String aBuffer = "";
while ((aDataRow = myReader.readLine()) != null) {
aBuffer += aDataRow + "\n";
}
txtData2.setText(aBuffer);
myReader.close();
Toast.makeText(getBaseContext(),
"Done reading SD 'mysdfile.txt'",
Toast.LENGTH_SHORT).show();
} catch (Exception e) {
Toast.makeText(getBaseContext(), e.getMessage(),
Toast.LENGTH_SHORT).show();
}
}
}
The first latout uses a linearlayout that contain an edittext and a button
The second a linearLayout with only a textview
Try it works fine if you find problem let me know!!
Ah i forget you have to add in your manifest
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>

I found reason. Problem was in fragment:
while ((length = fis.read(buffer)) != -1) {
String temp = new String(buffer, 0,length);
messageString.append(temp);
fis.close();
}
What's the catch?
fis.close();
should be after while. I didn't notice that yesterday...

Related

compiling cpp files on runtime Android Studio

I am making a compiling app with my custom made a language. This app will change the custom made language code automatically to a CPP code. So all I need to do is compile the CPP code on runtime.
I got stuck compiling a CPP file in my app.
I have already checked out using dexmaker and image-playground, but I had problems with the Gradle-build. They are somewhat old projects and I'm not really sure how to use it so I passed that one.
So I am trying to use the command line tool with the android studio. I have saved my CPP file and can use it I think. Below includes my file i/o code. This is my code.
Code:
public class Code_cpp extends AppCompatActivity {
private Context context;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.code_cpp);
TextView textView = (TextView) findViewById(R.id.view);
textView.setMovementMethod(new ScrollingMovementMethod());
context = this;
}
public void savebutton(View v) {
final EditText edit = (EditText) findViewById(R.id.edit_text);
TextView textView = (TextView) findViewById(R.id.view);
Log.v("EditText", edit.getText().toString());
String messageString = edit.getText().toString();
writeToFile(messageString,context);
Toast.makeText(getApplicationContext(), "saved", Toast.LENGTH_LONG).show();
}
private void writeToFile(String data,Context context) {
try {
OutputStreamWriter outputStreamWriter = new OutputStreamWriter(context.openFileOutput("config.cpp", Context.MODE_PRIVATE));
outputStreamWriter.write(data);
outputStreamWriter.close();
Log.e("Success", "File write Success ");
}
catch (IOException e) {
Log.e("Exception", "File write failed: " + e.toString());
}
}
public void loadbutton(View v){
String msg = readFromFile(context);
TextView textView = (TextView) findViewById(R.id.view);
textView.setText(msg);
}
private String readFromFile(Context context) {
String ret = "";
try {
InputStream inputStream = context.openFileInput("config.cpp");
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).append("\n");
}
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;
}
public void run(View v){
try {
Process process = Runtime.getRuntime().exec("g++ config.cpp;./a.out");
BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
int read;
char[] buffer = new char[4096];
StringBuffer output = new StringBuffer();
while ((read = reader.read(buffer)) > 0) {
output.append(buffer, 0, read);
}
reader.close();
// Waits for the command to finish.
process.waitFor();
//return output.toString();
String result=output.toString();
TextView textView = (TextView) findViewById(R.id.view);
textView.setText(result);
} catch (IOException e) {
throw new RuntimeException(e);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
}
}
I get an error when I click the run button
Caused by: java.io.IOException: Cannot run program "g++": error=13, Permission denied
I don't want to root my phone because I don't want to use this app just on my phone but with other phones too when I download it. Do I have to try another way to compile this? Why do I get permission denied errors?

read and write in a file android

I have next problems:
(1) How to check whether a file exists ? I do it this way in MainActivity onCreate
File f = new File("punteggio.txt");
if(f.exist())
readFromFile();
else{
writeToFile();
readFromFile();
}
but it does not work because every time I open my application file does not exist.
(2) Another problem.
In my first activity I write and read from the file without problems, while in the second activity when I read from the file the string is empty .
Main activity
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textScore = (TextView) findViewById(R.id.textRecord);
File f = new File("punteggio.txt");
if (!f.exists()) {
Log.d(TAG, "Writeee");
writeToFile();
} else {
readFromFile();
}
}
private void readFromFile() {
String ret = "";
try {
FileInputStream fis = openFileInput("punteggio.txt");
byte[] buffer = new byte[(int) fis.getChannel().size()];
fis.read(buffer);
String str = "";
for (byte b : buffer) str += (char) b;
fis.close();
Log.d(TAG, str);
textScore.setText("Record: " + str);
Log.i("STACKOVERFLOW", String.format("GOT: [%s]", str));
} catch (IOException e) {
Log.e("STACKOVERFLOW", e.getMessage(), e);
}
}
public void startGame(View v) {
Intent i = new Intent(MainActivity.this, GamePanel.class);
startActivity(i);
}
private void writeToFile() {
String string = "0";
try {
FileOutputStream fos = openFileOutput("punteggio.txt", Context.MODE_PRIVATE);
fos.write(string.getBytes());
fos.flush();
fos.close();
} catch (IOException e) {
Log.e(TAG, e.getMessage(), e);
}
}
This is the secondActivity
private int readFromFile() {
String str = "";
int i = 0;
try {
FileInputStream fis = openFileInput("punteggio.txt");
byte[] buffer = new byte[(int) fis.getChannel().size()];
fis.read(buffer);
for (byte b : buffer) str += (char) b;
i = Integer.parseInt(str);
fis.close();
} catch (IOException e) {
Log.e("STACKOVERFLOW", e.getMessage(), e);
}
Log.d(TAG, "Stringa iiiii: " + i);
return i;
}
The variable is empty, why?
Can you help me? Thanks
answer for (1) - opening and writing to file depend on where the file is located, it could be in phone storage OR in SD Card. as such, when implementing reading files system, care should be taken considering the location of the file. This, sometime will cause the error, cannot locating the file.
Alternatively, a better way of doing it would be using share preference.
sidenote : storing game score in a text file is vulnerable because user can directly edit the scores in the text file and alter the game result.

Android save to file.txt appending

I admittedly am still learning and would consider myself a novice (at best) regarding programming. I am having trouble with appending a file in android. Whenever I save, it will rewrite over the file, and I am having trouble understanding how to keep the file that is already there and only add a new line. Hoping for some clarity/advice. Here is how I am saving to the file (which rewrites the file each time I save).
public void saveText(View view){
try {
//open file for writing
OutputStreamWriter out = new OutputStreamWriter(openFileOutput("save.txt", MODE_PRIVATE));
//write information to file
EditText text = (EditText)findViewById(R.id.editText1);
String text2 = text.getText().toString();
out.write(text2);
out.write('\n');
//close file
out.close();
Toast.makeText(this,"Text Saved",Toast.LENGTH_LONG).show();
} catch (java.io.IOException e) {
//if caught
Toast.makeText(this, "Text Could not be added",Toast.LENGTH_LONG).show();
}
}
Change this,
OutputStreamWriter out = new OutputStreamWriter(openFileOutput("save.txt", MODE_PRIVATE));
to,
OutputStreamWriter out = new OutputStreamWriter(openFileOutput("save.txt", Context.MODE_APPEND));
This will append your new contents to the already existing file.
I Hope it helps!
Use this method, pass filename and the value to be added in the file
public void writeFile(String mValue) {
try {
String filename = Environment.getExternalStorageDirectory()
.getAbsolutePath() + mFileName;
FileWriter fw = new FileWriter("ENTER_YOUR_FILENAME", true);
fw.write(mValue + "\n\n");
fw.close();
} catch (IOException ioe) {
}
}
To display the content of the saved file with the line breaks with a button click use:
b2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
try {
FileInputStream fin = openFileInput(fileTitle);
int c;
String temp = "";
while ((c = fin.read()) != -1) {
temp = temp + Character.toString((char) c);
}
tv.setText(temp);
Toast.makeText(getBaseContext(), "file read", Toast.LENGTH_SHORT).show();
} catch (Exception e) {
}
}
});
To Delete content of existing file whist retaining the filename you can use:
deleteOrder.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
try {
FileOutputStream fOut = openFileOutput(fileTitle,MODE_PRIVATE);
// fOut.write(data.getBytes());
dataTitle = "";
fOut.write(data.getBytes());
fOut.close();
}
catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
This worked for me. Takes content of a TextEdit called textTitle. Writes it to file called dataTitle. Then writes a new line with fOut.write("\n"). The next text entered into TextEdit is added to the file with a line break.
try {
FileOutputStream fOut = openFileOutput(fileTitle,MODE_APPEND);
fOut.write(dataTitle.getBytes());
fOut.write('\n');
fOut.close();
Toast.makeText(getBaseContext(),"file saved",Toast.LENGTH_SHORT).show();
}
catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});

Overwriting data using files

i created a file and when i run the program, the data is been written in to the file but when i run the program again the new data over write on old data.
i need once the program is running and gathers data, these data are writable into the file in cascade next each other without overwriting on previous data in file.
this code running successful but when i run the program again the over writing happens which i don need that, i need to save previous data in side the file and write the new data next it and soon.
after edit this code its looks like:
public class MainActivity extends Activity {
File file;
File sdCard;
FileOutputStream fos;
OutputStreamWriter myOutWriter;
String FileName = "Output3.txt";
String eol;
OutputStream fos1;
FileWriter fw ;
BufferedWriter writer;
BufferedWriter bw ;
PrintWriter out;
EditText txtData;
Button btnWriteSDFile;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
sdCard =getExternalFilesDir(null);
file = new File(sdCard,FileName);
txtData = (EditText) findViewById(R.id.editText1);
btnWriteSDFile = (Button) findViewById(R.id.button1);
btnWriteSDFile.setOnClickListener(new OnClickListener()
{
public void onClick(View v)
{
try {
fos = new FileOutputStream(file);
myOutWriter =new OutputStreamWriter(fos);
eol = System.getProperty("line.separator");
writer = new BufferedWriter(myOutWriter);
writer.append(txtData.getText() + eol);// write this text.
writer.flush();
fos.close();
Toast.makeText(v.getContext(),"Done writing SD 'Output.txt'", Toast.LENGTH_SHORT).show();
txtData.setText("");
} catch (Exception e) {
// e.printStackTrace();
Toast.makeText(v.getContext(), e.getMessage(),Toast.LENGTH_SHORT).show();
}
finally{
try {
fos.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
});
}
please,can any one answer me?
Instead of using OutputStreamWriter use Filewriter FileWriter fileWritter = new FileWriter(file,true); when u pass true it appends the contents.try this
FileWriter myOutWriter = new FileWriter(file.getName(),true);
eol = System.getProperty("line.separator");
writer = new BufferedWriter(myOutWriter);
writer.write(txtData.getText() + eol);// write this text.
writer.close();
fos.close();
Change this line:
fos = new FileOutputStream(file);
To:
fos = new FileOutputStream(file, true);
This opens the file so that data can be appended.
JavaDocs for FileOutputStream
use
FileWriter writer = new FileWriter("yourfilename", true);
second parameter should be passed as true which will append data instead of overwriting
try {
File myFile = new File(Environment.getExternalStorageDirectory() + File.separator + "test.txt");
// this changed bye fos = new FileOutputStream(myFile) to
fos = new FileOutputStream(myFile,true);
//FileWriter writer = new FileWriter("yourfilename", true);
myOutWriter = new OutputStreamWriter(fos);
eol = System.getProperty("line.separator");
writer = new BufferedWriter(myOutWriter);
writer.append("\n");
writer.append(txtData.getText() + eol);// write this text.
writer.flush();
fos.close();
Toast.makeText(v.getContext(),
"Done writing SD 'Output.txt'", Toast.LENGTH_SHORT)
.show();
txtData.setText("");
} catch (Exception e) {
// e.printStackTrace();
Toast.makeText(v.getContext(), e.getMessage(),
Toast.LENGTH_SHORT).show();
} finally {
try {
fos.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
Enjoye i have tested it is work for me.

write into a file and read it to save the content into a variable like String

firstly, i search an answer everywhere but i didn't found.
Thank you very much for your answers.
In fact, i try to write into a file. Then, i try to save the content into a StringBuffer. And finally i try to show it via a TextView, but it shows nothing!
public class MainActivity extends Activity {
String finall;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
String FILENAME = "hello_file";
String string = "hello world!";
FileOutputStream fos;
try
{
fos = openFileOutput(FILENAME, Context.MODE_PRIVATE);
fos.write(string.getBytes());
fos.close();
}
catch (FileNotFoundException e) { e.printStackTrace(); }
catch (IOException e) { e.printStackTrace(); }
FileInputStream in = null;
try
{
in = openFileInput("hello_file.txt");
StringBuffer fileContent = new StringBuffer("");
byte[] buffer = new byte[1024];
while(in.read(buffer) != -1)
{
fileContent.append(new String(buffer));
}
finall = fileContent.toString();
}
catch (FileNotFoundException e) { e.printStackTrace(); }
catch (IOException e) { e.printStackTrace(); }
TextView text = (TextView)findViewById(R.id.mehmet);
text.setText(finall);
}
}
Try closing your FileInputStream after the read is finished as you did with FileOutputStream. This makes the data get flushed.
As said by #Piovezan you should close your file, but you should also consider that the intended valued returned by in.read(buffer) may not be equal to buffer.length
So you could have some dirty values at the end. And I don't know if this is your case but StringBuffer is thread safe, so if you aren't working in a multi thread section of your app you could switch to StringBuilder for better performance and less overhead

Categories

Resources