Java file read and write [Memo]

xiaoxiao2021-03-06  16

Package FileAccess;

Import java.io. *; import java.awt.event. *; import java.util. *; import javax.swing. *;

/ ** * Title: * Description: This is a bean * Copyright: Copyright (C) 2001 2001/11/24 * Company: Hainan Online Technology * @Version 1.0 * @Author Program Hunter /

Public Class FileAccess {Private String FileName, ErrorMessage; Private Int Columns, RowCount

/ * Structural function of textfileReader * / public fileAccess () {reset ();

Public void reset () {filename = new string (""); errorMessage = new string (""); columns = 0; rowcount = 0;}

Public void setErrorMessage (String ErrorMessage) {this.ErrorMessage = ErrorMessage;

Public string getErrorMessage () {return errorMessage;}

Public string getFilename () {return filename;}

Public int getRows () {Return Rowcount;}

Public int getColumns () {return column;}

/ * Return the contents of the file to a string to return to null * / public string getcontent () {string content = ""; file file file = new file (file n);

IF (! file.exists ()) {SeterrorMessage ("Error: the file '" filename "' does not exists"); return content;} else if (file! = null) {Try {bufferedreader reader = new bufferedReader NEW FileReader (File); string inline = reader.readline ();

While (inline! = null) {if (inline.Length () 1> columns = inline.LENGTH () 1;

Content = (INLINE System.getProperty ("line.separator"); inline = reader.readline (); rowcount ;}

Return Content;

} Catch (ieException e) {setErrorMessage ("Error Reading The File:"; Return Content;}} else {SETERRORMESSAGE ("Unknown Error!"); Return Content;}}

/ * TextFileWriter part * /

Public void setfilename (string filename) {this.filename = filename;}

/ *

There are 2 ways to write new content writtenmod for files. A: If the file exists, the new content is appended to the file. Otherwise, create a new file O: If the file exists, overwrite the contents of the old file. Otherwise create a new file Writer: Wang Haibo 2001/11/30

* /

Public Boolean Write (String StrinputContent, Char Writemod) {Try {file fso = new file (filename);

String strcontent = new string ("" ");

BufferedWriter Writer = New BufferedWriter (New FileWriter (FSO));

Switch (Writemod) {case 'a': // The most new content to the file

FileAccess objfread = new fileAccess (); string oldcontent = new string ("");

Objfread.setFileName (filename); OldContent = ObjFread.getContent ();

StrContent = OldContent StrinputContent;

Break;

Case 'o': // New content coverage the content of the old file

StrContent; Break;

DEFAULT:

StrContent; Break;

Writer.write (strcontent);

Writer.close ();

Return True;

} Catch (ioexception e) {setErrorMessage ("Error Writting the file:" E.GETMESSAGE ()); Return False;}

}

}

转载请注明原文地址:https://www.9cbs.com/read-46871.html

New Post(0)