Exercise : 16
Create an application to read file from asset
folder and copy it in memory card.
Screen Shot:
XML :
s1.xml :
JAVA :
SixteenActivity.java :
s1.xml :
JAVA :
SixteenActivity.java :
package kmn.Sixteen;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.widget.Toast;
public class SixteenActivity extends Activity
{
/** @author Y@@D */
FileOutputStream fos ;
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.s1);
try
{
String destPath = "/sdcard/kmn.txt";
File f = new File(destPath);
if (!f.exists())
{
CopyDB( getBaseContext().getAssets().open("file.txt"),new FileOutputStream(destPath));
}
Intent i = new Intent(SixteenActivity.this,screen1.class);
startActivity(i);
}
catch (Exception e)
{
Toast.makeText(SixteenActivity.this, " "+e.toString(), Toast.LENGTH_LONG).show();
}
}
public void CopyDB(InputStream inputStream,OutputStream outputStream)throws IOException
{
//---copy 1K bytes at a time---
byte[] buffer = new byte[1024];
int length;
while ((length = inputStream.read(buffer)) > 0)
{
outputStream.write(buffer, 0, length);
}
inputStream.close();
outputStream.close();
}
}
screen1.java :
package kmn.Sixteen;
import java.io.DataInputStream;
import java.io.File;
import java.io.FileInputStream;
import android.app.Activity;
import android.os.Bundle;
import android.os.Environment;
import android.widget.TextView;
import android.widget.Toast;
public class screen1 extends Activity
{
/** @author Y@@D */
public void onCreate(Bundle b)
{
super.onCreate(b);
setContentView(R.layout.s1);
try
{
File fileDir = Environment.getExternalStorageDirectory();
File directory = new File(fileDir.getAbsolutePath());
File file = new File(directory , "kmn.txt");
FileInputStream fis = new FileInputStream(file);
String str = null;
StringBuffer sbuffer = new StringBuffer();
DataInputStream dataio = new DataInputStream(fis);
while((str = dataio.readLine()) != null)
{
sbuffer.append(str + "\n");
}
TextView txt=(TextView)findViewById(R.id.showTxt);
txt.setText(sbuffer);
}
catch (Exception e)
{
Toast.makeText(this, " "+e.toString(), Toast.LENGTH_LONG).show();
}
}
}
