我有一个程序读取文件我可以更改此文件的内容,然后将其写入另一个文件。输入文件如下所示: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();
}
}
}
答案 0 :(得分:0)
更新代码,在阅读文件时,您将做出决定:
int sevenCount = 0;
int fourteenCount = 0;
int data = 0;
while ((data = reader.read()) != -1) {
sevenCount++;
fourteenCount++;
if(sevenCount==7)
{
buf.append("-"); // append - at every 7th character
sevenCount = 0;
}
if(fourteenCount==14)
{
buf.append("\n"); // change line after evrry 14th character
fourteenCount = 0;
}
if(((char)data) == '*')
{
char c = '!'; //Change the code when char contain *
data = (int)c;
}
else
{
buf.append((char)data);
}
}
答案 1 :(得分:0)
如果你想每12个字符在字符串中插入一个换行符:
str = str.replaceAll(".{12}", "$0\n");