注册百度的开发者后,获得自己对应的App ID,Api Key ,Secret Key
首先在maven中添加
<dependency> <groupId>com.baidu.aip</groupId> <artifactId>java-sdk</artifactId> <version>4.11.0</version> </dependency>
package ZTH.main; import java.io.File; import java.util.HashMap; import java.util.Scanner; import org.json.JSONArray; import org.json.JSONObject; import com.baidu.aip.ocr.AipOcr; /** * Hello world! * */ public class App { public static final String APP_ID = "XXXX"; public static final String API_KEY = "XXX"; public static final String SECRET_KEY = "XXX"; public static final String Url = "https://aip.baidubce.com/rest/2.0/ocr/v1/general_basic "; public static void main( String[] args ) { System.out.println( "程序启动" ); @SuppressWarnings("resource") Scanner ReadPath = new Scanner(System.in); System.out.println( "请输入图片文件夹路径" ); String path=ReadPath.nextLine(); AipOcr client = new AipOcr(APP_ID, API_KEY, SECRET_KEY); client.setConnectionTimeoutInMillis(2000); client.setSocketTimeoutInMillis(60000); File file = new File(path); func(file,client); System.out.println( "程序运行完毕" ); } private static void func(File file,AipOcr client) { File[] fs = file.listFiles(); for(File f:fs) { if(f.isDirectory()) func(f,client); if(f.isFile()) { JSONObject res = client.basicGeneral(f.getPath(), new HashMap<String, String>());//获取链接信息 //处理识别信息 JSONArray res1 =res.getJSONArray("words_result"); String name=res1.getJSONObject(0).getString("words"); //System.out.println(res1);//拼接字符串中的字符 处理错误信息 name=name.replaceAll("/", "1"); name=name.replaceAll("\.", ""); System.out.println(name); String name1=name.substring(4); name1=name1.replaceAll("S", "5"); name1=name1.replaceAll("O", "0"); name1=name1.replaceAll("o", "0"); name=name.substring(0, 4)+name1; //处理后缀名 String path=f.getParent(); String Old_name=f.getName(); String[] strarray=Old_name.split("\.", 2); String type=strarray[1]; name=name+"."+type; String newFlie=path+"\" +name; File newName = new File(newFlie); if(f.renameTo(newName)) { System.out.println("已重命名"); } else { System.out.println("Error"); } } } } }