这就是我要形成一个应该写入文件的多行字符串..
Base64 encoder = new Base64(64,System.getProperty("line.separator").getBytes());
String cert_begin = "-----BEGIN CERTIFICATE-----"+ System.getProperty("line.separator");
String end_cert = System.getProperty("line.separator")+"-----END CERTIFICATE-----";
byte[] derCert = cert.getEncoded();
String pemCertPre = new String(encoder.encode(derCert));
String pemCert = cert_begin + pemCertPre + end_cert;
return pemCert;
下面显示了用于编写文件的代码..
String PEMString = convertToPem(cert);
FileWriter PEMWriter = new FileWriter(PEMFile, false);
PEMWriter.write(PEMString);
//flush the file
PEMWriter.flush();
当我写信给文件的时候,pemCertPre就是用一行编写的。
导入Base64 来自
org.apache.tomcat.util.codec.binary.Base64
答案 0 :(得分:0)
嘿,我在写文件时使用BufferedWriter。也许你可以尝试一下。我在main方法中编写了一个基本的编写器作为示例,另外两个方法是针对您遇到的问题。但是在第一个方法中存在错误covertToPem()我认为cert是type" Certificate"
希望这有帮助。
public static void main(String args[]){
File file = new File("subfolder/path/fileName.txt");
String a = "one";
String b = "two";
char ch = 't';
try {
BufferedWriter writer = new BufferedWriter(new FileWriter(file));
writer.write(a);
writer.newLine(); //makes new line
writer.write(b);
writer.newLine();
writer.write(ch);
writer.newLine();
writer.flush();
writer.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
//try is instead
private String[] convertToPem(Certificate cert){
String[] pemCert = new String[3];
try{
Base64 encoder = new Base64(64,System.getProperty("line.separator").getBytes());
String cert_begin = "-----BEGIN CERTIFICATE-----"+ System.getProperty("line.separator");
String end_cert = System.getProperty("line.separator")+"-----END CERTIFICATE-----";
byte[] derCert = cert.getEncoded();
String pemCertPre = new String(encoder.encode(derCert));
}catch(Exception e){
e.printStackTrace();
}
return pemCert;
}
private void writeToFile(File fileLoaction){
Certificate cert = null;
String[] pemCert = convertToPem(cert);
try {
BufferedWriter writer = new BufferedWriter(new FileWriter(fileLoaction));
for(int i=0; i<pemCert.length; i++){
writer.write(pemCert[i]);
writer.newLine();
}
writer.flush();
writer.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
进口
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.Writer;
import java.security.cert.Certificate;
import com.sun.org.apache.xerces.internal.impl.dv.util.Base64;