Java file reading and writing,

Source: Internet
Author: User
/**
*
*/
Package com.struts2.other;


Import Java.io.BufferedReader;
Import Java.io.BufferedWriter;
Import Java.io.File;
Import Java.io.FileInputStream;
Import Java.io.FileReader;
Import Java.io.FileWriter;
Import java.io.IOException;
Import Java.io.InputStream;
Import Java.io.InputStreamReader;
Import Java.io.Reader;
Import java.util.ArrayList;
Import Java.util.HashMap;
Import java.util.List;
Import Java.util.Map;


/**
* @author Administrator
*
*/
public class Writeintext {


/**
* @param args
*/
public static void Main (string[] args) {
try {
Savedatatofile ("/conf/data.txt");
catch (Exception e) {
E.printstacktrace ();
}
}


/**
* Writes the contents of data to a file in the specified path
*
* @param fileName
* @param string
* @throws IOException
*/
public static void Savedatatofile (String str) throws IOException {
File F = new file ("D:/data/data.txt");
if (!f.exists ()) {
CreateFile ();
}
BufferedReader br = new BufferedReader (new FileReader (f));
BufferedWriter bw = new BufferedWriter (new FileWriter (f));
String s= "The name and identity of the user you marked with the method or session";
BW = new Java.io.BufferedWriter (new
Java.io.OutputStreamWriter (Writerstream, "UTF-8"));
if (br.readline () = null) {
byte[] Midbytes = str.getbytes ("UTF8");
String srt2 = new String (midbytes, "UTF-8");
Bw.write (str);
Br.close ();
Bw.flush ();
Bw.close ();
}
}


/**
*
*/
public static void CreateFile () {


Path indicates the paths of the files you created
String Path = "D:/data";
File F = new file (path);
if (!f.exists ()) {
F.mkdirs ();
}
filename indicates the filename you created; txt type;
String fileName = "Data.txt";
File File = new file (f, fileName);
if (!file.exists ()) {
try {
File.createnewfile ();
catch (IOException e) {
TODO auto-generated Catch block
E.printstacktrace ();
}
}


}


/**
* Read files in behavior units, often used to read line-oriented format files
*/
public string Readfilebylines (string fileName) {
File File = new file (fileName);
BufferedReader reader = null;
String data= "";
try {
reader = new BufferedReader (new FileReader (file));
String tempstring = null;
int line = 1;
Read one line at a time until you read NULL to end the file
while ((tempstring = Reader.readline ())!= null) {
Show line Numbers
System.out.println (tempstring);
data=tempstring;
line++;
}
Reader.close ();
catch (IOException e) {
E.printstacktrace ();
finally {
if (reader!= null) {
try {
Reader.close ();
catch (IOException E1) {
}
}
}
return data;
}


/**
* Read files in characters, often used to read text, numbers, and other types of files
*
* @param fileName
*/
public static void Readfilebychars (String fileName) {
File File = new file (fileName);
Reader reader = null;
try {
Read multiple characters at a time
char[] Tempchars = new CHAR[30];
int charread = 0;
reader = new InputStreamReader (fileName) (new FileInputStream);
Reads multiple characters into a character array, charread the number of characters read at a time
while ((Charread = Reader.read (tempchars))!=-1) {
Same shielding. \ r does not display
if ((Charread = = tempchars.length)
&& (Tempchars[tempchars.length-1]!= ")" {
System.out.print (Tempchars);
} else {
for (int i = 0; i < Charread; i++) {
if (tempchars[i] = = ' \ r ') {
Continue
} else {
System.out.print (Tempchars[i]);
}
}
}
}


catch (Exception E1) {
E1.printstacktrace ();
finally {
if (reader!= null) {
try {
Reader.close ();
catch (IOException E1) {
}
}
}
}

}

One. Obtain information entered by the console user

     public String getinputmessage () throws IOException ... {
         system.out.println ("Please enter your command:");
         byte buffer[]=new byte[1024];
         int count=system.in.read (buffer);
         char[] ch=new char[count-2];//last two digits as Terminator, delete no
          for (int i=0;i<count-2;i++)
              ch[i]= (char) buffer[i];
         string str=new String (CH);
         return str;
     }
      can return information entered by the user, the disadvantage is that the Chinese input is not supported, pending further improvement.

two. copy Files
1. Copying files in a file flow manner

public void CopyFile (String src,string dest) throws IOException ... {
FileInputStream in=new FileInputStream (SRC);
File File=new file (dest);
if (!file.exists ())
File.createnewfile ();
FileOutputStream out=new fileoutputstream (file);
int C;
byte buffer[]=new byte[1024];
while ((C=in.read (buffer))!=-1 ... {
for (int i=0;i<c;i++)
Out.write (Buffer[i]);
}
In.close ();
Out.close ();
}
This method has been tested to support Chinese processing and can be replicated in a variety of formats such as Txt,xml,jpg,doc

three. Write a document

1. Use PrintStream to write files


public void Printstreamdemo () ... {
Try ... {
FileOutputStream out=new FileOutputStream ("D:/test.txt");
PrintStream p=new PrintStream (out);
for (int i=0;i<10;i++)
P.println ("This is" +i+ "line");
catch (FileNotFoundException e) ... {
E.printstacktrace ();
}
}
2. Use StringBuffer to write files
public void Stringbufferdemo () throws IOException ... {
File File=new file ("/root/sms.log");
if (!file.exists ())
File.createnewfile ();
FileOutputStream out=new FileOutputStream (file,true);
for (int i=0;i<10000;i++) ... {
StringBuffer sb=new StringBuffer ();
Sb.append ("This is the first" +i+ "line: The various methods described earlier are not closed, why is always a strange problem");
Out.write (Sb.tostring (). GetBytes ("Utf-8"));
}
Out.close ();
}
This method can be used to set the code to effectively solve the Chinese problem.
four. File renaming

public void RenameFile (String path,string oldname,string newname) ... {
if (!oldname.equals (newname)) ... {//new file name is not the same as previous filename, it is necessary to rename
File Oldfile=new file (path+ "/" +oldname);

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.