Jumat, 15 Februari 2019
Android Kriptograph RSA+AES
Pada Menu Login:
Kode Login:
Button btnLogin= (Button) findViewById(R.id.btnLogin);
btnLogin.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String user=txtusername.getText().toString();
String pass=txtpassword.getText().toString();
if(user.length()<1){lengkapi("Username");}
else if(pass.length()<1){lengkapi("Password");}
else{
int index=-1;
if(pilih.equalsIgnoreCase("Karyawan")){
for(int i=0;i<jd;i++){
if(user.equalsIgnoreCase(arNik[i]) && pass.equalsIgnoreCase(arNik[i])){
index=i;
break;
}
}
if(index<0){
gagal();
}
else{
key=arPrivate[index]+"#"+arN[index]+"#"+arNama[index]+"#"+arNik[index]+"#";
sukses("Karyawan "+arNama[index]);//
}
}
else{
if(user.equalsIgnoreCase("admin") && pass.equalsIgnoreCase("admin")){sukses("Admin");}
else if(user.equalsIgnoreCase("hrd") && pass.equalsIgnoreCase("hrd")){sukses("HRD");}
else{gagal();}
}
}
}
});
Jadi jika sebagai admin atau hrd akan menuju ke halaman Enkrip dan Pengujian
dan jika sebagai karyawan akan menuju ke halaman Dekrip dan Buka Dokumen
di halaman Index juga tersedia initialisasi dataUji yaitu daftar nama nama karyawan yang bisa menggunakan aplikasi ini (sample contoh):
Inisialisasi dataUji:
void loadkar(){
jd=5;
arNik=new String[jd];
arNama=new String[jd];
arNik[0]="50815317";
arNama[0]="Geum Jan Di";
arNik[1]="24117371";
arNama[1]="Gu Jun Pyo";
arNik[2]="10616173";
arNama[2]="Yoon Ji Hoo";
arNik[3]="19515731";
arNama[3]="Song Woo Bin";
arNik[4]="70114713";
arNama[4]="So Yi Jung";
}
Pada Menu utama Admin/HRD
Kode Saat memilih dokumen (Open file):
txtnama.setOnClickListener(new View.OnClickListener() {
@Override public void onClick(View v) {
try {
Intent gintent = new Intent();
Uri mydir = Uri.parse(mypath);
gintent.setDataAndType(mydir, "*/*");
gintent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(gintent, "Select Data"),PICK_IMAGE);
} catch (Exception e) {
Toast.makeText(getApplicationContext(), e.getMessage(), Toast.LENGTH_LONG).show();
Log.e(e.getClass().getName(), e.getMessage(), e);
}
}
Kode Saat Button Proses ditekan:
Tergantung Option radiobutton yang dipilih sebelumnya:
btnProcess.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View arg0) {
cetak(filePath);
if( statusbaca.equalsIgnoreCase("Encrypt")){
enkrip();
Toast.makeText(Aplikasi.this, "Proses Encrypt "+filePath, Toast.LENGTH_SHORT).show();
}
else if( statusbaca.equalsIgnoreCase("Decrypt")){
dekrip();
Toast.makeText(Aplikasi.this, "Proses Decrypt "+filePath, Toast.LENGTH_SHORT).show();
}
else{
Toast.makeText(Aplikasi.this, "Load Path "+filePath, Toast.LENGTH_SHORT).show();
File x=new File(filePath);
openFile(x);
}
SBB adalah kode Open File sesuai extensi file ybs:
private void openFile(File url) {
Intent intent = new Intent(Intent.ACTION_VIEW);
try {
Uri uri = Uri.fromFile(url);
if (url.toString().contains(".doc") || url.toString().contains(".docx")) {
// Word document
intent.setDataAndType(uri, "application/msword");
} else if (url.toString().contains(".pdf")) {
// PDF file
intent.setDataAndType(uri, "application/pdf");
} else if (url.toString().contains(".ppt") || url.toString().contains(".pptx")) {
// Powerpoint file
intent.setDataAndType(uri, "application/vnd.ms-powerpoint");
} else if (url.toString().contains(".xls") || url.toString().contains(".xlsx")) {
// Excel file
intent.setDataAndType(uri, "application/vnd.ms-excel");
} else if (url.toString().contains(".zip") || url.toString().contains(".rar")) {
// WAV audio file
intent.setDataAndType(uri, "application/x-wav");
} else if (url.toString().contains(".rtf")) {
// RTF file
intent.setDataAndType(uri, "application/rtf");
} else if (url.toString().contains(".wav") || url.toString().contains(".mp3")) {
// WAV audio file
intent.setDataAndType(uri, "audio/x-wav");
} else if (url.toString().contains(".gif")) {
// GIF file
intent.setDataAndType(uri, "image/gif");
} else if (url.toString().contains(".jpg") || url.toString().contains(".jpeg") || url.toString().contains(".png")) {
// JPG file
intent.setDataAndType(uri, "image/jpeg");
} else if (url.toString().contains(".txt")) {
// Text file
intent.setDataAndType(uri, "text/plain");
} else if (url.toString().contains(".3gp") || url.toString().contains(".mpg") ||
url.toString().contains(".mpeg") || url.toString().contains(".mpe") || url.toString().contains(".mp4") || url.toString().contains(".avi")) {
// Video files
intent.setDataAndType(uri, "video/*");
} else {
intent.setDataAndType(uri, "*/*");
}
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
} catch (ActivityNotFoundException e) {
Toast.makeText(this, "No application found which can open the file", Toast.LENGTH_SHORT).show();
}
}
Proses Enkrip:
1.Membuat File menjadi byte
FileInputStream inputStream = null;
try {
inputStream = new FileInputStream(nf);
} catch (IOException e) {
e.printStackTrace();
}
byte[] buffer = new byte[1024];//8192
int bytesRead=0;
ByteArrayOutputStream output = new ByteArrayOutputStream();
try {
while ((bytesRead = inputStream.read(buffer)) != -1) {
output.write(buffer, 0, bytesRead);
}
} catch (IOException e) {
e.printStackTrace();
}
byte bytePath[] = output.toByteArray();
2.data Byte array yang didapatkan di RSA KAN
byte []data=bytePath;
String[] data1 = new String[data.length];
for(int i=0; i < data.length; i++) {
data1[i] = String.valueOf(data[i] & 0xff); //unsigned integer
}
BigInteger[] data2 = new BigInteger[data1.length];
for (int i = 0; i < data1.length; i++) {
data2[i] = (new BigInteger(data1[i])).pow(this.e);
data2[i] = data2[i].mod(this.n);
}
String[] x = new String[data2.length];
for(int i = 0; i < data2.length; i++) {
x[i] = String.valueOf(data2[i]);
}
String data5 = StringUtils.join(x, " ");
3.String data hasil RSA di AES kan
AES128 aes128 = new AES128();
String cipherText = aes128.encrypt(data5,256,passAES);
4.hasil Chipertext RSA+AES ahir disimpan ke dalam file hasil dekrip
try {
String content = dataEncrypt;
File file = new File(this.fileNameEncrypt);
if (!file.exists()) {
file.createNewFile();
}
FileWriter fw = new FileWriter(file.getAbsoluteFile());
BufferedWriter bw = new BufferedWriter(fw);
bw.write(content);
bw.close();
} catch (IOException e) {
e.printStackTrace();
}
5.Hasil File bisa di open untuk melihat hasilnya menggunaan kode open file berdasarkan extensi di atas
PROSES DEKRIP:
1.Membuat File menjadi deretan String
BufferedReader be = null;
String current;
String data = "";
be = new BufferedReader(new FileReader(fileName));
while ((current = be.readLine()) != null) {
data += current;
}
2.String data adalah isi daripada file Enkripsi sebelumnya selanjutnya melakukan proses Dekripsi
pertama data String tersebut di dekrip AES
AES128 aes128 = new AES128();
String plainText = aes128.decrypt(data, 256, passAES);
3.String Dekrip AES selanjutnya di Dekrip RSA
String[] data1 = plainText.split(" ");
BigInteger[] data2 = new BigInteger[data1.length];
for (int i=0; i < data1.length; i++){
data2[i] = (new BigInteger(String.valueOf(data1[i]))).pow(this.d);
data2[i] = data2[i].mod(this.n);
}
byte[] data3 = new byte[data2.length];
String[] x = new String[data2.length];
String gab="";
for (int i=0; i < data2.length; i++){
data3[i] = (byte) (data2[i].byteValue());
}
4.Hasil byte array yang di dapat selanjutnay disimpan ke dalam file
File file=new File("Nama File Dekrip");
try {
FileOutputStream fileOutputStream = new FileOutputStream(file);
fileOutputStream.write(data3);
fileOutputStream.flush();
fileOutputStream.close();
return file.toString();
} catch (IOException e) {
e.printStackTrace();
return null;
}
5.Hasil File bisa di open untuk melihat hasilnya menggunaan kode open file berdasarkan extensi di atas
Sabtu, 09 Februari 2019
Library FIle SDCARD dll
package id.ac.istn.appkripto;
//https://www.dev2qa.com/android-read-write-external-storage-file-example/
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.channels.FileChannel;
import android.app.Activity;
import android.app.ActionBar;
import android.app.Fragment;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import android.widget.Toast;
import android.os.Build;
public class appSD extends Activity {
private TextView textView;
String TAG="isiq";
@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textView = (TextView)findViewById(R.id.txt1);
bacaFile("/storage/sdcard0/FILEPROJEK/en.uji5.txt");
bacaisiSD();
// bacaFile("/storage/sdcard0/FILEPROJEK/en.uji1.pdf");
// bacaFile("/storage/sdcard0/FILEPROJEK/dec.en.uji1.pdf");
//buatfile();
// bacaFile();
// String pathsd=getPathSD()+File.separator+"myData";
// Log.v("pathsd",pathsd);
// createDirIfNotExists(pathsd);
//
// baca(pathsd+File.separator+"tes.txt");
// bacaFile();
// File folder = new File(Environment.getExternalStorageDirectory().toString()+"\\myDataAPPA");
// folder.mkdirs();
//
// String extStorageDirectory = folder.toString();
// Log.v("extStorageDirectory",extStorageDirectory);
// // bacaisiSD();
// //copyFileOrDirectory("/storage/sdcard0/tes1.txt","/storage/sdcard0/FILEPROJEK/");
// try {
// copy("/storage/sdcard0/tes1.txt","/storage/sdcard0/FILEPROJEK/tes1.txt");
// } catch (IOException e) {
// // TODO Auto-generated catch block
// e.printStackTrace();
// }
}
void buatfile(){
if (!Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)){
//handle case of no SDCARD present
} else {
String dir = Environment.getExternalStorageDirectory()+File.separator+"ADI";
//create folder
File folder = new File(dir); //folder name
folder.mkdirs();
Log.v("BUAT","Berhasil="+dir);
Toast.makeText(this, dir, Toast.LENGTH_LONG).show();
//create file
File file = new File(dir, "filename.txt");
File files = new File(dir, "out.txt");
FileOutputStream os = null;
try {
os = new FileOutputStream(files);
} catch (FileNotFoundException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
String datas ="Selamat Pagi Bro kamu OK?";// "This is the content of my file";
try {
os.write(datas.getBytes());
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
try {
os.close();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
//++++++++++++++++++++++++++++++
// bacaisiSD();
// bacaFile("/storage/sdcard0/uji1.txt");
// bacaFile("/storage/sdcard0/FILEPROJEK/en.uji1.txt");
// bacaFile("/storage/sdcard0/FILEPROJEK/dec.uji1.txt");
}
}
public void copy(String ssrc, String sdst) throws IOException {
File src=new File(ssrc);
File dst=new File(sdst);
InputStream in = new FileInputStream(src);
try {
OutputStream out = new FileOutputStream(dst);
try {
// Transfer bytes from in to out
byte[] buf = new byte[1024];
int len;
while ((len = in.read(buf)) > 0) {
out.write(buf, 0, len);
}
} finally {
out.close();
}
} finally {
in.close();
}
}
void bacaisiSD(){
final String state = Environment.getExternalStorageState();
File file = Environment.getExternalStorageDirectory();
String abs=file.getAbsolutePath();
Log.v("isiabs",abs);
if ( Environment.MEDIA_MOUNTED.equals(state) || Environment.MEDIA_MOUNTED_READ_ONLY.equals(state) ) { // we can read the External Storage...
getAllFilesOfDir(Environment.getExternalStorageDirectory());
}
}
private void getAllFilesOfDir(File directory) {//Streaming.jpg
// //String al="/storage/sdcard0/WhatsApp/Media/WhatsApp Documents/";//directory.getAbsolutePath()+"/FILEPROJEK/";
//
// File mfile = Environment.getExternalStorageDirectory();
//String abs=mfile.getAbsolutePath();
// Log.v("isiabs",abs);
//String al=abs+"/FILEPROJEK/";
// Log.v("isiabs2",al);
// directory=new File(al);
String abs=directory.getAbsolutePath();
Log.v("isiabs",abs);
String al=abs+"/FILEPROJEK/";
directory=new File(al);
Log.d(TAG, "Directory: " + directory.getAbsolutePath() + "\n");
final File[] files = directory.listFiles();
if ( files != null ) {
for ( File file : files ) {
if ( file != null ) {
if ( file.isDirectory() ) { // it is a folder...
getAllFilesOfDir(file);
}
else { // it is a file...
Log.d(TAG, "File: " + file.getAbsolutePath() + "\n");
}
}
}
}
}
void bacaFile(String baca){
String state = Environment.getExternalStorageState();
if (!(state.equals(Environment.MEDIA_MOUNTED))) {
Toast.makeText(this, "There is no any sd card", Toast.LENGTH_LONG).show();
} else {
BufferedReader reader = null;
try {
File file = Environment.getExternalStorageDirectory();
String abs=file.getAbsolutePath();
Log.v("isiabs",abs);
// Toast.makeText(this, "Sd card available "+abs, Toast.LENGTH_LONG).show();
// File textFile = new File(file.getAbsolutePath()+File.separator+ "tes1.txt");
//String abs2=textFile.getAbsolutePath();
// Log.v("isiabs2",abs2);
// Toast.makeText(this, "Sd card available "+abs2, Toast.LENGTH_LONG).show();
//
reader = new BufferedReader(new FileReader(baca));//tes1.txt
StringBuilder textBuilder = new StringBuilder();
String line;
String gab="";
while((line = reader.readLine()) != null) {
gab+=line;
textBuilder.append(line);
textBuilder.append("\n");
}
textView.setText(textBuilder);
Log.v("isi",baca+"="+gab);
} catch (FileNotFoundException e) {
// TODO: handle exception
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
finally{
if(reader != null){
try {
reader.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
}
String getPathSD(){
String abs="";
String state = Environment.getExternalStorageState();
if (!(state.equals(Environment.MEDIA_MOUNTED))) {
Toast.makeText(this, "There is no any sd card", Toast.LENGTH_LONG).show();
} else {
try {
File file = Environment.getExternalStorageDirectory();
abs=file.getAbsolutePath();
Toast.makeText(this, "Sd card available :"+abs, Toast.LENGTH_LONG).show();
} catch (Exception e) {
e.printStackTrace();
}
}
return abs;
}
public static boolean createDirIfNotExists(String path) {
boolean ret = true;
File file = new File(Environment.getExternalStorageDirectory(), path);
if (!file.exists()) {
if (!file.mkdirs()) {
Log.e("TravellerLog :: ", "Problem creating Image folder");
ret = false;
}
}
return ret;
}
public static void copyFileOrDirectory(String srcDir, String dstDir) {
try {
File src = new File(srcDir);
File dst = new File(dstDir, src.getName());
if (src.isDirectory()) {
String files[] = src.list();
int filesLength = files.length;
for (int i = 0; i < filesLength; i++) {
String src1 = (new File(src, files[i]).getPath());
String dst1 = dst.getPath();
copyFileOrDirectory(src1, dst1);
}
} else {
copyFile(src, dst);
}
} catch (Exception e) {
e.printStackTrace();
}
}
public static void copyFile(File sourceFile, File destFile) throws IOException {
if (!destFile.getParentFile().exists())
destFile.getParentFile().mkdirs();
if (!destFile.exists()) {
destFile.createNewFile();
}
FileChannel source = null;
FileChannel destination = null;
try {
source = new FileInputStream(sourceFile).getChannel();
destination = new FileOutputStream(destFile).getChannel();
destination.transferFrom(source, 0, source.size());
} finally {
if (source != null) {
source.close();
}
if (destination != null) {
destination.close();
}
}
}
}
//https://www.dev2qa.com/android-read-write-external-storage-file-example/
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.channels.FileChannel;
import android.app.Activity;
import android.app.ActionBar;
import android.app.Fragment;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import android.widget.Toast;
import android.os.Build;
public class appSD extends Activity {
private TextView textView;
String TAG="isiq";
@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textView = (TextView)findViewById(R.id.txt1);
bacaFile("/storage/sdcard0/FILEPROJEK/en.uji5.txt");
bacaisiSD();
// bacaFile("/storage/sdcard0/FILEPROJEK/en.uji1.pdf");
// bacaFile("/storage/sdcard0/FILEPROJEK/dec.en.uji1.pdf");
//buatfile();
// bacaFile();
// String pathsd=getPathSD()+File.separator+"myData";
// Log.v("pathsd",pathsd);
// createDirIfNotExists(pathsd);
//
// baca(pathsd+File.separator+"tes.txt");
// bacaFile();
// File folder = new File(Environment.getExternalStorageDirectory().toString()+"\\myDataAPPA");
// folder.mkdirs();
//
// String extStorageDirectory = folder.toString();
// Log.v("extStorageDirectory",extStorageDirectory);
// // bacaisiSD();
// //copyFileOrDirectory("/storage/sdcard0/tes1.txt","/storage/sdcard0/FILEPROJEK/");
// try {
// copy("/storage/sdcard0/tes1.txt","/storage/sdcard0/FILEPROJEK/tes1.txt");
// } catch (IOException e) {
// // TODO Auto-generated catch block
// e.printStackTrace();
// }
}
void buatfile(){
if (!Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)){
//handle case of no SDCARD present
} else {
String dir = Environment.getExternalStorageDirectory()+File.separator+"ADI";
//create folder
File folder = new File(dir); //folder name
folder.mkdirs();
Log.v("BUAT","Berhasil="+dir);
Toast.makeText(this, dir, Toast.LENGTH_LONG).show();
//create file
File file = new File(dir, "filename.txt");
File files = new File(dir, "out.txt");
FileOutputStream os = null;
try {
os = new FileOutputStream(files);
} catch (FileNotFoundException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
String datas ="Selamat Pagi Bro kamu OK?";// "This is the content of my file";
try {
os.write(datas.getBytes());
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
try {
os.close();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
//++++++++++++++++++++++++++++++
// bacaisiSD();
// bacaFile("/storage/sdcard0/uji1.txt");
// bacaFile("/storage/sdcard0/FILEPROJEK/en.uji1.txt");
// bacaFile("/storage/sdcard0/FILEPROJEK/dec.uji1.txt");
}
}
public void copy(String ssrc, String sdst) throws IOException {
File src=new File(ssrc);
File dst=new File(sdst);
InputStream in = new FileInputStream(src);
try {
OutputStream out = new FileOutputStream(dst);
try {
// Transfer bytes from in to out
byte[] buf = new byte[1024];
int len;
while ((len = in.read(buf)) > 0) {
out.write(buf, 0, len);
}
} finally {
out.close();
}
} finally {
in.close();
}
}
void bacaisiSD(){
final String state = Environment.getExternalStorageState();
File file = Environment.getExternalStorageDirectory();
String abs=file.getAbsolutePath();
Log.v("isiabs",abs);
if ( Environment.MEDIA_MOUNTED.equals(state) || Environment.MEDIA_MOUNTED_READ_ONLY.equals(state) ) { // we can read the External Storage...
getAllFilesOfDir(Environment.getExternalStorageDirectory());
}
}
private void getAllFilesOfDir(File directory) {//Streaming.jpg
// //String al="/storage/sdcard0/WhatsApp/Media/WhatsApp Documents/";//directory.getAbsolutePath()+"/FILEPROJEK/";
//
// File mfile = Environment.getExternalStorageDirectory();
//String abs=mfile.getAbsolutePath();
// Log.v("isiabs",abs);
//String al=abs+"/FILEPROJEK/";
// Log.v("isiabs2",al);
// directory=new File(al);
String abs=directory.getAbsolutePath();
Log.v("isiabs",abs);
String al=abs+"/FILEPROJEK/";
directory=new File(al);
Log.d(TAG, "Directory: " + directory.getAbsolutePath() + "\n");
final File[] files = directory.listFiles();
if ( files != null ) {
for ( File file : files ) {
if ( file != null ) {
if ( file.isDirectory() ) { // it is a folder...
getAllFilesOfDir(file);
}
else { // it is a file...
Log.d(TAG, "File: " + file.getAbsolutePath() + "\n");
}
}
}
}
}
void bacaFile(String baca){
String state = Environment.getExternalStorageState();
if (!(state.equals(Environment.MEDIA_MOUNTED))) {
Toast.makeText(this, "There is no any sd card", Toast.LENGTH_LONG).show();
} else {
BufferedReader reader = null;
try {
File file = Environment.getExternalStorageDirectory();
String abs=file.getAbsolutePath();
Log.v("isiabs",abs);
// Toast.makeText(this, "Sd card available "+abs, Toast.LENGTH_LONG).show();
// File textFile = new File(file.getAbsolutePath()+File.separator+ "tes1.txt");
//String abs2=textFile.getAbsolutePath();
// Log.v("isiabs2",abs2);
// Toast.makeText(this, "Sd card available "+abs2, Toast.LENGTH_LONG).show();
//
reader = new BufferedReader(new FileReader(baca));//tes1.txt
StringBuilder textBuilder = new StringBuilder();
String line;
String gab="";
while((line = reader.readLine()) != null) {
gab+=line;
textBuilder.append(line);
textBuilder.append("\n");
}
textView.setText(textBuilder);
Log.v("isi",baca+"="+gab);
} catch (FileNotFoundException e) {
// TODO: handle exception
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
finally{
if(reader != null){
try {
reader.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
}
String getPathSD(){
String abs="";
String state = Environment.getExternalStorageState();
if (!(state.equals(Environment.MEDIA_MOUNTED))) {
Toast.makeText(this, "There is no any sd card", Toast.LENGTH_LONG).show();
} else {
try {
File file = Environment.getExternalStorageDirectory();
abs=file.getAbsolutePath();
Toast.makeText(this, "Sd card available :"+abs, Toast.LENGTH_LONG).show();
} catch (Exception e) {
e.printStackTrace();
}
}
return abs;
}
public static boolean createDirIfNotExists(String path) {
boolean ret = true;
File file = new File(Environment.getExternalStorageDirectory(), path);
if (!file.exists()) {
if (!file.mkdirs()) {
Log.e("TravellerLog :: ", "Problem creating Image folder");
ret = false;
}
}
return ret;
}
public static void copyFileOrDirectory(String srcDir, String dstDir) {
try {
File src = new File(srcDir);
File dst = new File(dstDir, src.getName());
if (src.isDirectory()) {
String files[] = src.list();
int filesLength = files.length;
for (int i = 0; i < filesLength; i++) {
String src1 = (new File(src, files[i]).getPath());
String dst1 = dst.getPath();
copyFileOrDirectory(src1, dst1);
}
} else {
copyFile(src, dst);
}
} catch (Exception e) {
e.printStackTrace();
}
}
public static void copyFile(File sourceFile, File destFile) throws IOException {
if (!destFile.getParentFile().exists())
destFile.getParentFile().mkdirs();
if (!destFile.exists()) {
destFile.createNewFile();
}
FileChannel source = null;
FileChannel destination = null;
try {
source = new FileInputStream(sourceFile).getChannel();
destination = new FileOutputStream(destFile).getChannel();
destination.transferFrom(source, 0, source.size());
} finally {
if (source != null) {
source.close();
}
if (destination != null) {
destination.close();
}
}
}
}
Open Assosiatif File Berdasarkan extensi
Button btnOpen=(Button)findViewById(R.id.btnOpen);
btnOpen.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View arg0) {
String paths=txtPath.getText().toString();
if(paths.indexOf(".pdf")>0){
File file = new File(Environment.getExternalStorageDirectory(), paths);
Uri path = Uri.fromFile(file);
Intent pdfOpenintent = new Intent(Intent.ACTION_VIEW);
pdfOpenintent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
pdfOpenintent.setDataAndType(path, "application/pdf");
try {
startActivity(pdfOpenintent);
}
catch (ActivityNotFoundException e) {
}
}
else{
File x=new File(paths);
openFile(x);
}
}});
+++++++++++++++++++++++++++++++++++++++
private void openFile(File url) {
Intent intent = new Intent(Intent.ACTION_VIEW);
try {
Uri uri = Uri.fromFile(url);
if (url.toString().contains(".doc") || url.toString().contains(".docx")) {
// Word document
intent.setDataAndType(uri, "application/msword");
} else if (url.toString().contains(".pdf")) {
// PDF file
intent.setDataAndType(uri, "application/pdf");
} else if (url.toString().contains(".ppt") || url.toString().contains(".pptx")) {
// Powerpoint file
intent.setDataAndType(uri, "application/vnd.ms-powerpoint");
} else if (url.toString().contains(".xls") || url.toString().contains(".xlsx")) {
// Excel file
intent.setDataAndType(uri, "application/vnd.ms-excel");
} else if (url.toString().contains(".zip") || url.toString().contains(".rar")) {
// WAV audio file
intent.setDataAndType(uri, "application/x-wav");
} else if (url.toString().contains(".rtf")) {
// RTF file
intent.setDataAndType(uri, "application/rtf");
} else if (url.toString().contains(".wav") || url.toString().contains(".mp3")) {
// WAV audio file
intent.setDataAndType(uri, "audio/x-wav");
} else if (url.toString().contains(".gif")) {
// GIF file
intent.setDataAndType(uri, "image/gif");
} else if (url.toString().contains(".jpg") || url.toString().contains(".jpeg") || url.toString().contains(".png")) {
// JPG file
intent.setDataAndType(uri, "image/jpeg");
} else if (url.toString().contains(".txt")) {
// Text file
intent.setDataAndType(uri, "text/plain");
} else if (url.toString().contains(".3gp") || url.toString().contains(".mpg") ||
url.toString().contains(".mpeg") || url.toString().contains(".mpe") || url.toString().contains(".mp4") || url.toString().contains(".avi")) {
// Video files
intent.setDataAndType(uri, "video/*");
} else {
intent.setDataAndType(uri, "*/*");
}
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
} catch (ActivityNotFoundException e) {
Toast.makeText(this, "No application found which can open the file", Toast.LENGTH_SHORT).show();
}
}
btnOpen.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View arg0) {
String paths=txtPath.getText().toString();
if(paths.indexOf(".pdf")>0){
File file = new File(Environment.getExternalStorageDirectory(), paths);
Uri path = Uri.fromFile(file);
Intent pdfOpenintent = new Intent(Intent.ACTION_VIEW);
pdfOpenintent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
pdfOpenintent.setDataAndType(path, "application/pdf");
try {
startActivity(pdfOpenintent);
}
catch (ActivityNotFoundException e) {
}
}
else{
File x=new File(paths);
openFile(x);
}
}});
+++++++++++++++++++++++++++++++++++++++
private void openFile(File url) {
Intent intent = new Intent(Intent.ACTION_VIEW);
try {
Uri uri = Uri.fromFile(url);
if (url.toString().contains(".doc") || url.toString().contains(".docx")) {
// Word document
intent.setDataAndType(uri, "application/msword");
} else if (url.toString().contains(".pdf")) {
// PDF file
intent.setDataAndType(uri, "application/pdf");
} else if (url.toString().contains(".ppt") || url.toString().contains(".pptx")) {
// Powerpoint file
intent.setDataAndType(uri, "application/vnd.ms-powerpoint");
} else if (url.toString().contains(".xls") || url.toString().contains(".xlsx")) {
// Excel file
intent.setDataAndType(uri, "application/vnd.ms-excel");
} else if (url.toString().contains(".zip") || url.toString().contains(".rar")) {
// WAV audio file
intent.setDataAndType(uri, "application/x-wav");
} else if (url.toString().contains(".rtf")) {
// RTF file
intent.setDataAndType(uri, "application/rtf");
} else if (url.toString().contains(".wav") || url.toString().contains(".mp3")) {
// WAV audio file
intent.setDataAndType(uri, "audio/x-wav");
} else if (url.toString().contains(".gif")) {
// GIF file
intent.setDataAndType(uri, "image/gif");
} else if (url.toString().contains(".jpg") || url.toString().contains(".jpeg") || url.toString().contains(".png")) {
// JPG file
intent.setDataAndType(uri, "image/jpeg");
} else if (url.toString().contains(".txt")) {
// Text file
intent.setDataAndType(uri, "text/plain");
} else if (url.toString().contains(".3gp") || url.toString().contains(".mpg") ||
url.toString().contains(".mpeg") || url.toString().contains(".mpe") || url.toString().contains(".mp4") || url.toString().contains(".avi")) {
// Video files
intent.setDataAndType(uri, "video/*");
} else {
intent.setDataAndType(uri, "*/*");
}
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
} catch (ActivityNotFoundException e) {
Toast.makeText(this, "No application found which can open the file", Toast.LENGTH_SHORT).show();
}
}
EditText Load File
//membaca working dinamic directory
// File rootDataDir = Aplikasi.this.getFilesDir();
// Log.v("PATHME", rootDataDir.toString());///data/data/id.ac.istn.appkripto/files
//membaca absolute directory
File file = Environment.getExternalStorageDirectory();
mypath=file.getAbsolutePath();
mypathOut=mypath+"/app_gaji/";//app_gaji
boolean mdir=createDirIfNotExists(mypathOut);
Log.d(TAG,"Status make directory "+mypathOut+":"+mdir);
txtnama=(EditText)findViewById(R.id.txtnama);
txtnama.setText(mypathOut);
txtnama.setOnClickListener(new View.OnClickListener() {
@Override public void onClick(View v) {
try {
Intent gintent = new Intent();
Uri mydir = Uri.parse(mypathOut);//default address :/storage/sdcard0/app_gaji
gintent.setDataAndType(mydir, "*/*");
//gintent.setType("image/*|application/pdf|audio/*");
//gintent.setType("image/*");//PDF image
gintent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(gintent, "Select Data"),PICK_IMAGE);
} catch (Exception e) {
Toast.makeText(getApplicationContext(), e.getMessage(), Toast.LENGTH_LONG).show();
Log.e(e.getClass().getName(), e.getMessage(), e);
}
}
});
+++++++++
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
String filePath="";
Uri selectedImageUri = null;
switch (requestCode) {
case PICK_IMAGE:
if (resultCode == Activity.RESULT_OK) { selectedImageUri = data.getData(); }
break;
}
if(selectedImageUri != null){
String A1 = selectedImageUri.getPath();
String B1 = getPath(selectedImageUri);
if (B1 != null) {
filePath = B1;
Log.v("filePath1",filePath);
} else if (A1 != null) {
filePath = A1;
Log.v("filePath2",filePath);
} else {
Toast.makeText(getApplicationContext(), "Unknown path", Toast.LENGTH_LONG).show();
Log.e("filePath", "Unknown path");
}
Log.v("PATHME","A1:"+A1+"#B1:"+B1+"#"+filePath);
if(filePath.indexOf(":")>0 || (filePath+"").length()<4){
txtnama.setText("");
Toast.makeText(getApplicationContext(), "Unknown path :"+filePath, Toast.LENGTH_LONG).show();
}
else{
txtnama.setText(filePath);
txtPath.setText("");
txtTime.setText("");
txtNote.setText("");
}
}
}
maka file akan terbuka dimanapun dia berada
Jangan Lupa permissionnya:
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
Langganan:
Postingan (Atom)