Java Simple file read and write, yesterday helped students write a simple file processing program, record this side, unexpectedly spent one hours, is because System.out print log when the location of the wrong:-(
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; Line number Marker
Boolean flag = false; The switch splicing switch that appears to the ++++
Boolean output = false; Output the contents of this pair in ++++
while ((data = Br.readline ()) = null) {
Count + +;
Output = false;
if (Data.contains (sampletxt) && count > 2) {
if (!flag) {
In addition to the first line, the first occurrence of ++++ begins append until the second ++++
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 ();
}
}
Another method:
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 ()) {
File Rename
Readfile.renameto (New File (Filename+filerenamesuffix));
}
ReadFile = new File (filename+filerenamesuffix);
int sampletype = 1; Fill 1 for Syncsample_spam.txt, 2 for Syncsample_normal.txt
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 ()) {
Specifies that read files are read in UTF-8 format
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;
}
Java Simple file Read and write