我正在尝试获取docx文件,如下所示
private let MaxLuck = 1000.0
public extension Double {
public static func random(lower: Double = 0, _ upper: Double = 100, luck: Double) -> Double {
let weight = min(luck / MaxLuck, 1)
return (Double(arc4random()) / 0xFFFFFFFF) * weight * (upper - lower) + lower
}
}
现在的结果是:
路径: public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == MainActivity.RESULT_OK) {
if (resultCode == RESULT_OK) {
// Get the Uri of the selected file
Uri uri = data.getData();
String uriString = uri.toString();
File myFile = new File(uriString);
String path = myFile.getAbsolutePath();
filepath =path;
String displayName = null;
if (uriString.startsWith("content://")) {
Cursor cursor = null;
try {
cursor = this.getContentResolver().query(uri, null, null, null, null);
if (cursor != null && cursor.moveToFirst()) {
displayName = cursor.getString(cursor.getColumnIndex(OpenableColumns.DISPLAY_NAME));
txtFilename.setText(displayName);
filename = displayName;
}
} finally {
cursor.close();
}
} else if (uriString.startsWith("file://")) {
displayName = myFile.getName();
txtFilename.setText(displayName);
filename = displayName;
}
}
}
}
文件名:/content:/com.estrongs.files/storage/emulated/0/Download/Imp%20Values.docx
现在如何将此文档转换为base64?
提前致谢。
答案 0 :(得分:5)
试试这个,希望它能起作用,我为.pdf和.doc
做了// Create new stopwatch.
Stopwatch stopwatch = new Stopwatch();
// Begin timing.
stopwatch.Start();
// Do something.
for (int i = 0; i < 1000; i++)
{
Thread.Sleep(1);
}
// Stop timing.
stopwatch.Stop();
// Write result.
Console.WriteLine("Time elapsed: {0}", stopwatch.Elapsed);
选择文件:
public static String convertFileToByteArray(File f) {
byte[] byteArray = null;
try {
InputStream inputStream = new FileInputStream(f);
ByteArrayOutputStream bos = new ByteArrayOutputStream();
byte[] b = new byte[1024 * 11];
int bytesRead = 0;
while ((bytesRead = inputStream.read(b)) != -1) {
bos.write(b, 0, bytesRead);
}
byteArray = bos.toByteArray();
Log.e("Byte array", ">" + byteArray);
} catch (IOException e) {
e.printStackTrace();
}
return Base64.encodeToString(byteArray, Base64.NO_WRAP);
}
答案 1 :(得分:0)
上面的代码总是返回nullpointerexception,但这解决了它而没有任何错误
// Converting File to Base64.encode String type using Method
public String getStringFile(File f) {
InputStream inputStream = null;
String encodedFile= "", lastVal;
try {
inputStream = new FileInputStream(f.getAbsolutePath());
byte[] buffer = new byte[10240];//specify the size to allow
int bytesRead;
ByteArrayOutputStream output = new ByteArrayOutputStream();
Base64OutputStream output64 = new Base64OutputStream(output, Base64.DEFAULT);
while ((bytesRead = inputStream.read(buffer)) != -1) {
output64.write(buffer, 0, bytesRead);
}
output64.close();
encodedFile = output.toString();
}
catch (FileNotFoundException e1 ) {
e1.printStackTrace();
}
catch (IOException e) {
e.printStackTrace();
}
lastVal = encodedFile;
return lastVal;
}