我正在尝试使用'\ 034'字段分隔符作为字符串中的分隔符。 问题是当我硬编码“\ 034”+ opField并将其写入文件时,但是如果从文件中读取“\ 034”字符,它会将输出写为字符串“col1 \ 034col2”。 我尝试使用StringBuilder,但它将\ 034转义为“\\ 034”。 我使用以下代码从文件中读取字符:
try (BufferedReader br = new BufferedReader(new FileReader(fConfig))){
int lc = 1;
for(String line;(line = br.readLine())!=null;){
String[] rowList = line.split(delim);
int row_len = rowList.length;
if (row_len<2){
System.out.println("Incorrect dictionary file row:"+fConfig.getAbsolutePath()+"\nNot enough values found at row:"+line);
}else{
String key = rowList[0];
String value = rowList[1];
dictKV.put(key, value);
}
lc++;
}
}catch(Exception e){
throw e;
}
欢迎任何帮助......
[更新]:使用'\ t'字符也会发生同样的事情,如果编码很好,但如果从文件中读取它会附加为字符。 “COL0 \ tcol1”
if(colAl.toLowerCase().contains(" as ")){
String temp = colAl.replaceAll("[ ]+as[ ]+"," | ");
ArrayList<String> tempA = this.brittle_delim(temp,'|');
colAl = tempA.get(tempA.size()-1);
colAl = colAl.trim();
}else {
ArrayList<String> tempA = this.brittle_delim(colAl,' ');
colAl = tempA.get(tempA.size()-1);
colAl = colAl.trim();
}
if(i==0){
sb.append(colAl);
headerCols+=colAl.trim();
}else{
headerCols+= this.output_field_delim + colAl;
sb.append(this.output_field_delim);
sb.append(colAl);
}
}
}
System.out.println("SB Header Cols:"+sb.toString());
System.out.println("Header Cols:"+headerCols);
输出:
SB Header Cols: SPRN_CO_ID \ 034FISC_YR_MTH_DSPLY_CD \ 034CST_OBJ_CD \ 034PRFT_CTR_CD \ 034LEGL_CO_CD \ 034HEAD_CT_TYPE_ID \ 034FIN_OWN_CD \ 034FUNC_AREA_CD \ 034HEAD_CT_NR
Header Cols: SPRN_CO_ID \ 034FISC_YR_MTH_DSPLY_CD \ 034CST_OBJ_CD \ 034PRFT_CTR_CD \ 034LEGL_CO_CD \ 034HEAD_CT_TYPE_ID \ 034FIN_OWN_CD \ 034FUNC_AREA_CD \ 034HEAD_CT_NR
在上面的代码中,如果我执行以下操作,我会得到正确的结果:
headerCols+= "\034"+ colAl;
输出: SPRN_CO_IDFISC_YR_MTH_DSPLY_CDCST_OBJ_CDPRFT_CTR_CDLEGL_CO_CDHEAD_CT_TYPE_IDFIN_OWN_CDFUNC_AREA_CDHEAD_CT_NR FS角色即使在这里被删除也会存在
答案 0 :(得分:0)
您应该提供一个示例来说明您的问题。不只是不完整的代码片段。
按照可运行的代码段执行您所解释的内容。
// create a file one line
byte[] bytes = "foo bar".getBytes(StandardCharsets.ISO_8859_1);
String fileName = "/tmp/foobar";
Files.write(Paths.get(fileName), bytes);
String headerCols = "";
String outputFieldDelim = "\034";
try (BufferedReader br = new BufferedReader(new FileReader(fileName))) {
// read the line from the file and split by blank character
String[] cols = br.readLine().split(" ");
// contcatenate the values with "\034"
// but ... for your code ...
// don't concatenate String objects in a loop like below
// use a StringBuilder or StringJoiner instead
headerCols += outputFieldDelim + cols[0];
headerCols += outputFieldDelim + cols[1];
}
// output with the "\034" character
System.out.println(headerCols);
答案 1 :(得分:0)
我想这就是我找到解决方案的地方以及我的问题的实际用语。