1,创建文件
public static File createFile(String fileName) { File file = new File(fileName);//fileName是file路径,如String writeFilePath = "F:\\clpsmart\\clp.ldif"; try { if (!file.exists()) { file.createNewFile(); } StringBuilder strBuilder = new StringBuilder(); strBuilder.append("dn: ou=infocenter,dc=gionee,dc=com"+"\r\n"); strBuilder.append("objectClass: top"+"\r\n"); strBuilder.append("objectClass: organizationalUnit"+"\r\n"); strBuilder.append("ou: infocenter"+"\r\n"); strBuilder.append("\r\n"); FileOutputStream o = new FileOutputStream(fileName); o.write(strBuilder.toString().getBytes()); o.close(); } catch (Exception e) { e.printStackTrace(); } return file; }2,读取文件
public static void readTxtFile(String filePath, File fileName) { try { String encoding = "GBK"; File file = new File(filePath); if (file.isFile() && file.exists()) { //判断文件是否存在 InputStreamReader read = new InputStreamReader( new FileInputStream(file), encoding);//考虑到编码格式 BufferedReader bufferedReader = new BufferedReader(read); String lineTxt = null; Random random = new Random(); while ((lineTxt = bufferedReader.readLine()) != null) { String[] str = lineTxt.split("[\\p{Space}]+"); StringBuilder strBuilder = new StringBuilder(); strBuilder.append("dn: uid="+str[2]+",ou=infocenter,dc=gionee,dc=com"+"\r\n"); strBuilder.append("objectClass: posixAccount"+"\r\n"); strBuilder.append("objectClass: top"+"\r\n"); strBuilder.append("objectClass: inetOrgPerson"+"\r\n"); strBuilder.append("gidNumber: 0"+"\r\n"); String strUtfsn = ""; String strUtfcn = ""; for (int i = 0; i < str[1].length(); i++) { strUtfsn = str[1].substring(0, 1); strUtfcn += str[1].substring(i, i+1); } BASE64Encoder b = new BASE64Encoder(); strBuilder.append("sn::"+b.encode(strUtfsn.getBytes())+"\r\n"); strBuilder.append("displayName::"+b.encode(strUtfcn.getBytes())+"\r\n"); strBuilder.append("uid:"+str[2]+"\r\n"); strBuilder.append("homeDirectory: /"+"\r\n"); strBuilder.append("mail:"+str[3]+"\r\n"); strBuilder.append("cn::"+b.encode(strUtfcn.getBytes())+"\r\n"); strBuilder.append("uidNumber:"+Math.abs(random.nextInt())+ "\r\n"); strBuilder.append("userPassword: 123456"+"\r\n"); strBuilder.append("\r\n"); writeFile(strBuilder, fileName); } read.close(); } else { System.out.println("找不到指定的文件"); } } catch (Exception e) { System.out.println("读取文件内容出错"); e.printStackTrace(); } }3,写入文件
public static void writeFile(StringBuilder content, File fileName) throws Exception { FileOutputStream o = null; try { o = new FileOutputStream(fileName, true); OutputStreamWriter out = new OutputStreamWriter(o, "UTF-8"); BufferedWriter bufw = new BufferedWriter(out);//缓冲 bufw.write(content.toString()); bufw.close(); } catch (Exception e) { e.printStackTrace(); } }这里输出的是ldap的ldif文件,注意ldif文件中的数据行不能有空格。