标签:
Java简单文件读写, 昨天帮同学写了一个简单的文件处理程序,记录这边吧,竟然花了一个小时,就是因为system.out打印日志的时候位置写错了 :-(
public static void main(String[] args){
try{
BufferedReader br = new BufferedReader(new FileReader("D:/a.txt"));
File dest = new File("D:/b.txt");
BufferedWriter writer = new BufferedWriter(new FileWriter(dest));
String data = null;
String sampletxt = "++++";
StringBuffer strbf = null;
int count = 0; // 行数标记
boolean flag = false; // 本对++++出现的切换拼接开关
boolean output = false; // 输出本对 ++++内的内容
while((data = br.readLine()) != null){
count ++;
output = false;
if(data.contains(sampletxt) && count > 2){
if(!flag){
// 除了第一行之外,第一次出现++++即开始append,直到第二个++++
strbf = new StringBuffer();
flag = true;
}else{
flag = false;
if(strbf != null){
output = true;
strbf.append(data);
}
}
}
if(flag){
strbf.append(data);
}else{
if(!output){
writer.write(data+"\n");
System.out.println("----"+data);
}
}
if(output && (strbf != null) && (strbf.length() > 0)){
writer.write(strbf.toString());
System.out.println("----"+strbf.toString());
}
}
writer.flush();
br.close();
writer.close();
}catch(Exception ex){
ex.printStackTrace();
}
}
另外一个方法:
public List<UVO> readfileInfo(String fileName) throws FileNotFoundException,IOException{
List <UVO> list= new ArrayList<UVO>();
try{
uniportal_logger.trace("readfileInfo with fileName :"+ fileName);
File readfile = new File(fileName);
if(readfile.exists()){
// 文件重命名
readfile.renameTo(new File(fileName+fileRenameSuffix));
}
readfile = new File(fileName+fileRenameSuffix);
int sampletype = 1; // 为syncsample_spam.txt时填1,为syncsample_normal.txt时填2
if((fileName+fileRenameSuffix).toLowerCase().endsWith(filename_spam)){
sampletype = 1;
}else if((fileName+fileRenameSuffix).toLowerCase().endsWith(filename_normal)){
sampletype = 2;
}
if(readfile != null && readfile.exists() && !readfile.isDirectory()){
//指定读取文件时以UTF-8的格式读取
FileInputStream in = new FileInputStream(readfile);
BufferedReader br = new BufferedReader(new InputStreamReader(in,"UTF-8"));
String line = null;
while((line=br.readLine())!=null){
line = line.trim();
String ckresult = checkline(line);
if(ckresult.equals("")){
UVO entity = new UVO();
entity.setSampletype(sampletype);
entity.setSmcontent(line.trim().replaceAll(",", ","));
list.add(entity);
}
}
br.close();
in.close();
}
}catch(Exception ex){
ex.printStackTrace();
}
return list;
}
标签:
原文地址:http://blog.csdn.net/liu76xt/article/details/43052131