項目上的需要,C語言通過調用jar包去實作資料的處理,簡單總結了一下資料傳輸的方法
以之前做過的項目為例,C語言側取到了excel檔案,需要在java中對excel進行資料比對,然後将比對結果傳回C語言側。
1.在C語言中調用jar包是通過cmd指令執行的,先設計好完整的指令,然後執行。
char cmd[2048] = { ‘\0’ };
sprintf(cmd, "java -jar %s %s %s ", jarPath, excelPath, file_return);
system(cmd);
這裡的參數,jarPah是jar包路徑,excelPath是excel路徑,file_return是C和Java進行資料互動的中間檔案路徑,實際的完整指令如下:
java -jar D:test.jar C:test/test1234.xlsx C:\Users\TEMP\AppData\Local\Temp/testReturn.txt
其中互動的是中間檔案定義方法如下:
FILE *returnFile = NULL;
char file_return[128] = “”;
sprintf_s(file_return, “%s/testReturn.txt”, getenv(“TEMP”));
returnFile = createFile(file_return);
FILE* createFile(char* tmpFile)
{
int i=0;
FILE *matFile = NULL;
if((matFile = fopen(tmpFile, “w”))==NULL)
{
// 建立檔案失敗,此處可以輸出失敗Log.
}
return matFile;
}
2.java側回傳資料
把處理完的資料寫入中間件txt檔案中。這裡的filePath即C側傳過來的參數,直接使用即可。
private static void writeTxt(String filePath, String dataReturn)
throws Exception {
if(filePath != null)
{
BufferedWriter out = null;
out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(
filePath, true)));
out.write(dataReturn);
if (out != null)
out.close();
}
}
3.C側接收資料
FILE *txtfiler = NULL;
string returnUser = “”;
char buff[1024] = “”;
string errorMsg = “”;
if ((txtfiler = fopen(file_return, “r”)) != NULL)
{
while (!feof(txtfiler))
{
fgets(buff, 1024, txtfiler); // 從傳回檔案的第一行開始,每次讀一行資料
// errorMsg = errorMsg.append(buff);
}
// buff即傳回來的值
fclose(txtfiler);
}