【发布时间】:2014-02-10 09:10:57
【问题描述】:
我有一个读取文件的程序,我可以更改该文件的内容,然后将其写入另一个文件。输入文件看起来像这样:http://gyazo.com/4ee1ade01378238e2c765e593712de7f 输出必须看起来像这样 http://gyazo.com/5a5bfd00123df9d7791a74b4e77f6c10 我当前的输出是 http://gyazo.com/87a83f4c6d48aebda3d11060ebad66c2 那么如何更改我的代码,它在 12 个字符后开始新行?我也想删除最后一个!。
public class readFile {
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("-");
//buf.append(System.getProperty("line.separator"));
}
/* start with a new line if the line length is bigger than 12 - in progress*/
/* I know this if doesn't work but how to fix it? */
if (buf.length()>12){
buf.append(System.getProperty("line.separator"));
}
/* 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);
//buf.deleteCharAt(buf.length()-1);
}
// get last character from stringbuilder and delete
//buf.deleteCharAt(buf.length()-1);
}
}
public void writeFile() {
try {
String content = buf.toString();
File file = new File("C:/Users/Sybren/Desktop/test.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();
}
}
}
【问题讨论】:
-
最后是什么? 12 的最后一个字符?
-
当前输出中没有最后一个感叹号
-
您基本上是想将文件作为字符串获取,删除换行符,然后在每 12 个字符后输出一个换行符吗?
-
我想读取文件,进行一些更改并将其写入另一个文件。其中一项更改是每 12 个字符后开始换行。
标签: java bufferedreader stringbuilder bufferedwriter