AndroidApp/DocxHelper.java

75 lines
2.5 KiB
Java

package com.example.myapplication.Tool;
import android.content.Context;
import android.util.Log;
import android.widget.Toast;
import com.chaquo.python.PyObject;
import com.chaquo.python.Python;
import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
public class DocxHelper {
private static final String TAG = "DocxHelper";
public static File convertJsonToDocx(Context context, String jsonAssetName, String outputFileName) {
// 1. 从assets读取JSON数据
String jsonData = readJsonFromAssets(context, jsonAssetName);
if (jsonData == null) {
Toast.makeText(context, "Failed to read JSON from assets",Toast.LENGTH_SHORT).show();
return null;
}
// 2. 准备输出文件路径
File outputFile = new File(context.getExternalFilesDir(null), outputFileName);
String outputPath = outputFile.getAbsolutePath();
// 3. 调用Python处理
try {
Python py = Python.getInstance();
PyObject module = py.getModule("test");
// 调用Python函数
module.callAttr("json_to_docx", jsonData, outputPath);
Toast.makeText(context, "DOCX file generated at:"+outputPath, Toast.LENGTH_SHORT).show();
} catch (Exception e) {
Log.e(TAG, "Python processing failed", e);
}
finally {
return outputFile;
}
}
private static String readJsonFromAssets(Context context, String filename) {
try {
// 1. 打开assets中的文件输入流
InputStream is = context.getAssets().open(filename);
// 2. 创建缓冲读取器
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
// 3. 使用StringBuilder高效拼接字符串
StringBuilder sb = new StringBuilder();
String line;
// 4. 逐行读取文件内容
while ((line = reader.readLine()) != null) {
sb.append(line);
}
// 5. 关闭资源
reader.close();
// 6. 返回完整的JSON字符串
return sb.toString();
} catch (IOException e) {
Toast.makeText(context, "Error reading JSON file"+e.getMessage(), Toast.LENGTH_SHORT).show();
return null;
}
}
}