我有一个可以读取文件的类,修改它并将其写入另一个文件。输出中的字符是正确的,唯一的问题是这些行需要有12个字符的长度。 如何使用现有代码实现这一目标?(我在代码中写了一条评论,我想这样做)
My input file: http://gyazo.com/13fe791d24ef86e29ab6a6e89d0af609
The current output: http://gyazo.com/cc195c1d59a9d1fe3b4f2c54e71da8eb
The output I want : http://gyazo.com/04efcbb05c5d56b6e28972feb8c43fb8
String line;
StringBuilder buf = new StringBuilder();
public void readFile(){
BufferedReader reader = null;
try {
File file = new File("C:/Users/Sybren/Desktop/Invoertestbestand1.txt");
reader = new BufferedReader(new FileReader(file));
//String line;
while ((line = reader.readLine()) != null) {
System.out.println(line);
//buf.append(line);
processInput();
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
reader.close();
} catch (IOException e) {
e.printStackTrace();
};
}
}
public void processInput(){
buf.append(line);
if (buf.length()>7){
buf.append("-");
}
/* if a * is followed by * change them to a ! */
for (int index = 0; index < buf.length(); index++) {
if (buf.charAt(index) == '*' && buf.charAt(index+1) == '*') {
buf.setCharAt(index, '!');
buf.deleteCharAt(index+1);
}
}
// get last character from stringbuilder and delete
buf.deleteCharAt(buf.length()-1);
/* start with a new line if the line length is bigger than 12 - how to do it? */
//???
}
public void writeFile() {
try {
String content = buf.toString();
File file = new File("C:/Users/Sybren/Desktop/uitvoer1.txt");
// if file doesnt exists, then create it
if (!file.exists()) {
file.createNewFile();
}
FileWriter fw = new FileWriter(file.getAbsoluteFile());
BufferedWriter bw = new BufferedWriter(fw);
bw.write(content);
bw.close();
System.out.println("Done");
} catch (IOException e) {
e.printStackTrace();
}
}}
答案 0 :(得分:0)
这些内容会有所帮助吗?
for (int i=13;i<buf.size();i+=13) {
buf.insert(i, '\n');
i++; // to account for the newline char just added
}
使用的数字可能不正确,或者是因为对问题的误解,或者是因为没有经过测试。
答案 1 :(得分:0)
for (int index = 0; index < buf.length(); index++) {
if (buf.charAt(index) == '*' && buf.charAt(index+1) == '*') {
buf.setCharAt(index, '!');
buf.deleteCharAt(index+1);
}
}
当您调用index + 1
时,循环结束时会出现java.lang.ArrayIndexOutOfBoundsException