使用 Android Studio 将文件转换为字符串然后转换为 Base64 Fromate

Converting File into String then into Base64 Fromate With Android Studio

我想从 android 设备中选择一个文件,将该文件转换为字符串格式,将该字符串转换为 BASE64 编码,然后通过 API 将编码后的字符串传递给服务器。

我调试了我的项目,它转到了这一行:

  FileInputStream fis = new FileInputStream(new File(path));

它没有更进一步。

有人可以告诉我哪里做错了吗?

提前致谢。

这是我的代码:

      package com.example.deepb.testingencodingapp;

      import android.content.Intent;
      import android.net.Uri;
      import android.support.v7.app.AppCompatActivity;
      import android.os.Bundle;
      import android.util.Log;
      import android.view.View;
      import android.widget.Button;
      import android.widget.EditText;
      import android.widget.TextView;
      import android.util.Base64;
      import java.io.BufferedReader;
      import java.io.ByteArrayOutputStream;
      import java.io.File;
      import java.io.FileInputStream;
      import java.io.FileNotFoundException;
      import java.io.IOException;
      import java.io.InputStreamReader;


  public class MainActivity extends AppCompatActivity {

EditText fatchValue;
TextView displayValue,Fpath;
Button GetValue,SelectFile;
String  ret,uriString,finalString;
File myFile;
String line = null;
private static final int PICKFILE_RESULT_CODE = 1;
public static final int RESULT_OK = -1;
Uri uri;
byte[] fileBytes;



@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    fatchValue = findViewById(R.id.enterText);
    displayValue = findViewById(R.id.displayText);
    Fpath = findViewById(R.id.pathText);
    GetValue = findViewById(R.id.btn_go);
    SelectFile = findViewById(R.id.uploadFile);



    GetValue.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {

            String GotValue = fatchValue.getText().toString();
            byte[] encodeValue = Base64.encode(finalString.getBytes(), Base64.DEFAULT);
            String ansValue = encodeValue.toString();
            //displayValue.setText(ansValue);
            displayValue.setText(finalString);
            Log.d(finalString,"this is the String " + finalString);

        }
    });

    SelectFile.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            Intent getFile = new Intent(Intent.ACTION_GET_CONTENT);
            getFile.setType("*/*");
            startActivityForResult(getFile,PICKFILE_RESULT_CODE);
        }
    });
}

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    if (resultCode == RESULT_OK) {
        uri = data.getData();
        uriString = uri.toString();
        myFile = new File(uriString);
        ret = myFile.getAbsolutePath();
        Fpath.setText(ret);

        try {
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            String path = ret;
            FileInputStream fis = new FileInputStream(new File(path));

            byte[] buf = new byte[1024];
            int n;
            while (-1 != (n = fis.read(buf)))
                baos.write(buf, 0, n);

            fileBytes = baos.toByteArray();
            //Log.i("ByteArray" + path + ">><<" + ret, "----" + fileBytes.toString());
            finalString = fileBytes.toString();
        } catch (Exception e) {
            // TODO: handle exception
            e.printStackTrace();
        }
     }
public class DeppDemo extends AppCompatActivity {

EditText fatchValue;
TextView displayValue, Fpath;
Button GetValue, SelectFile;
String ret, uriString, finalString;
File myFile;
String line = null;
private static final int PICKFILE_RESULT_CODE = 1;
public static final int RESULT_OK = -1;
Uri uri;
byte[] fileBytes;
StringBuilder total = new StringBuilder();


String[] permissions = new String[]{
        android.Manifest.permission.READ_EXTERNAL_STORAGE,
        android.Manifest.permission.WRITE_EXTERNAL_STORAGE,
};

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    checkPermissions();

    displayValue = findViewById(R.id.displayText);
    Fpath = findViewById(R.id.pathText);
    GetValue = findViewById(R.id.btn_go);
    SelectFile = findViewById(R.id.uploadFile);


    GetValue.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {

            String s = "Man is distinguished, not only by his reason, but by this singular passion from other animals, which is a lust of the mind, that by a perseverance of delight in the continued and indefatigable generation of knowledge, exceeds the short vehemence of any carnal pleasure.";
            //String GotValue = fatchValue.getText().toString();
            // byte[] encodeValue = Base64.encode(finalString.getBytes(), Base64.DEFAULT);
            // byte[] encodeValue = Base64.encode(fileBytes, Base64.DEFAULT);
            byte[] encodeValue = Base64.encode(total.toString().getBytes(), Base64.DEFAULT);
            //byte[] encodeValue = Base64.encode(s.getBytes(), Base64.DEFAULT);
            String ansValue = encodeValue.toString();
            try {
                String text = new String(encodeValue, "UTF-8");
                displayValue.setText(text);

            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }

            //displayValue.setText(ansValue);
            Log.d(finalString, "this is the String " + finalString);

        }
    });

    SelectFile.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            Intent getFile = new Intent(Intent.ACTION_GET_CONTENT);
            getFile.setType("*/*");
            startActivityForResult(getFile, PICKFILE_RESULT_CODE);
        }
    });
}

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    if (resultCode == RESULT_OK) {
        uri = data.getData();
        uriString = uri.toString();


        try {
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            String path = ret;
            InputStream in = getContentResolver().openInputStream(uri);
            InputStreamReader inputStreamReader = new InputStreamReader(in);

            BufferedReader bufferedReader = new BufferedReader(inputStreamReader);

            String line;
            while ((line = bufferedReader.readLine()) != null) {
                total.append(line).append('\n');
            }


        } catch (Exception e) {
            // TODO: handle exception
            e.printStackTrace();
            Log.d("error", "onActivityResult: " + e.toString());
        }
    }
}

private boolean checkPermissions() {


    int result;
    List<String> listPermissionsNeeded = new ArrayList<>();
    for (String p : permissions) {
        result = ContextCompat.checkSelfPermission(this, p);
        if (result != PackageManager.PERMISSION_GRANTED) {
            listPermissionsNeeded.add(p);
        }
    }
    if (!listPermissionsNeeded.isEmpty()) {

        ActivityCompat.requestPermissions(this, listPermissionsNeeded.toArray(new String[listPermissionsNeeded.size()]), 100);
        return false;

    }
    return true;

}

}

它不是隐蔽的正确 base64,所以试试这个

    public class DeppDemo extends AppCompatActivity {

    EditText fatchValue;
    TextView displayValue, Fpath;
    Button GetValue, SelectFile;
    String ret, uriString, finalString;
    File myFile;
    String line = null;
    private static final int PICKFILE_RESULT_CODE = 1;
    public static final int RESULT_OK = -1;
    Uri uri;
    byte[] fileBytes;
    StringBuilder total = new StringBuilder();
    byte[] bytes;
    ByteArrayOutputStream output;




    String[] permissions = new String[]{
            android.Manifest.permission.READ_EXTERNAL_STORAGE,
            android.Manifest.permission.WRITE_EXTERNAL_STORAGE,
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        checkPermissions();

        displayValue = findViewById(R.id.displayText);
        Fpath = findViewById(R.id.pathText);
        GetValue = findViewById(R.id.btn_go);
        SelectFile = findViewById(R.id.uploadFile);


        GetValue.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {



//                String s = "Man is distinguished, not only by his reason, but by this singular passion from other animals, which is a lust of the mind, that by a perseverance of delight in the continued and indefatigable generation of knowledge, exceeds the short vehemence of any carnal pleasure.";
//                //String GotValue = fatchValue.getText().toString();
//                // byte[] encodeValue = Base64.encode(finalString.getBytes(), Base64.DEFAULT);
//                // byte[] encodeValue = Base64.encode(fileBytes, Base64.DEFAULT);
//                Log.d("image string", "onClick: "+total);
//                byte[] encodeValue = new byte[0];
//                try {
//                    encodeValue = Base64.encode(total.toString().getBytes("UTF-8"), Base64.DEFAULT);
//                } catch (UnsupportedEncodingException e) {
//                    e.printStackTrace();
//                }
//                //byte[] encodeValue = Base64.encode(s.getBytes(), Base64.DEFAULT);
//                String ansValue = encodeValue.toString();
//                try {
//                    String text = new String(encodeValue, "UTF-8");
//                    //displayValue.setText(text);
//                    Log.d("Base64", "onClick: "+text);
//                    Log.d("Base64 byte", "onClick: "+encodeValue);
//                    //String encodedString = Base64.encodeToString(bytes, Base64.DEFAULT);
//                    String encodedString = Base64.encodeToString(output.toByteArray(), Base64.DEFAULT);
//                    Log.d("Base64 ==2", "onClick: "+encodedString);
//
//
//                } catch (UnsupportedEncodingException e) {
//                    e.printStackTrace();
//                }
//
//                //displayValue.setText(ansValue);
//                Log.d(finalString, "this is the String " + finalString);

            }
        });

        SelectFile.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent getFile = new Intent(Intent.ACTION_GET_CONTENT);
                getFile.setType("*/*");
                startActivityForResult(getFile, PICKFILE_RESULT_CODE);
            }
        });
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            uri = data.getData();
            uriString = uri.toString();
            Log.d("data", "onActivityResult: uri"+uriString);
            //            myFile = new File(uriString);
            //            ret = myFile.getAbsolutePath();
            //Fpath.setText(ret);

            try {
                ByteArrayOutputStream baos = new ByteArrayOutputStream();
                String path = ret;
                InputStream in = getContentResolver().openInputStream(uri);

                bytes=getBytes(in);
                Log.d("data", "onActivityResult: bytes size="+bytes.length);

                Log.d("data", "onActivityResult: Base64string="+Base64.encodeToString(bytes,Base64.DEFAULT));


//                InputStreamReader inputStreamReader = new InputStreamReader(in);
//                BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
//                String line;
//                while ((line = bufferedReader.readLine()) != null) {
//                    total.append(line);
//                }
//                
//                byte[] buffer = new byte[8192];
//                int bytesRead;
//                output = new ByteArrayOutputStream();
//                int count=0;
//                try {
//                    while ((bytesRead = in.read(buffer)) != -1) {
//                        output.write(buffer, 0, bytesRead);
//                        count++;
//                    }
//                } catch (IOException e) {
//                    Log.d("error byte", "onActivityResult: " + e.toString());
//                    e.printStackTrace();
//                }
//                bytes = output.toByteArray();
//
//                Toast.makeText(this, "Done", Toast.LENGTH_SHORT).show();
                // FileInputStream fis = new FileInputStream(new File(uri.getPath()));

            //                byte[] buf = new byte[1024];
//                int n;
//                while (-1 != (n = in.read(buf))) {
//                    baos.write(buf, 0, n);
//                }
//                fileBytes = baos.toByteArray();
//                //Log.i("ByteArray" + path + ">><<" + ret, "----" + fileBytes.toString());
//                finalString = fileBytes.toString();


            } catch (Exception e) {
                // TODO: handle exception
                e.printStackTrace();
                Log.d("error", "onActivityResult: " + e.toString());
            }
        }
    }


    public byte[] getBytes(InputStream inputStream) throws IOException {
        ByteArrayOutputStream byteBuffer = new ByteArrayOutputStream();
        int bufferSize = 1024;
        byte[] buffer = new byte[bufferSize];

        int len = 0;
        while ((len = inputStream.read(buffer)) != -1) {
            byteBuffer.write(buffer, 0, len);
        }
        return byteBuffer.toByteArray();
    }

    private boolean checkPermissions() {


        int result;
        List<String> listPermissionsNeeded = new ArrayList<>();
        for (String p : permissions) {
            result = ContextCompat.checkSelfPermission(this, p);
            if (result != PackageManager.PERMISSION_GRANTED) {
                listPermissionsNeeded.add(p);
            }
        }
        if (!listPermissionsNeeded.isEmpty()) {

            ActivityCompat.requestPermissions(this, listPermissionsNeeded.toArray(new String[listPermissionsNeeded.size()]), 100);
            return false;

        }
        return true;

    }

}