Java writes a string to a file and reads the contents of the file to a string __ string writes to a file

Source: Internet
Author: User
Tags int size

writing a string to a file

Method One

public void Writestringtofile (String filePath) {
        try {
            file File = new file (FilePath);
            PrintStream PS = new PrintStream (new FileOutputStream (file));
            Ps.println ("http://www.jb51.net");//write String
            ps.append ("Http://www.jb51.net") to the file;//Add String on existing Foundation
        catch ( FileNotFoundException e) {
            //TODO auto-generated catch block
            e.printstacktrace ();
        }
    }

Method Two

  public void WriteStringToFile2 (String filePath) {
        try {
            FileWriter fw = new FileWriter (FilePath, true);
            BufferedWriter bw = new BufferedWriter (FW);
            Bw.append ("Add a string on an existing basis");
            Bw.write ("abc\r\n");//Add string to existing file
            bw.write ("def\r\n");
            Bw.write ("Hijk");
            Bw.close ();
            Fw.close ();
        } catch (Exception e) {
            //TODO auto-generated catch block
            e.printstacktrace ();
        }
    }
Method Three

public void WriteStringToFile3 (String filePath) {
        try {
            PrintWriter pw = new PrintWriter (New FileWriter (FilePath ));
            PW.PRINTLN ("abc");
            Pw.println ("def");
            Pw.println ("Hef");
            Pw.close ();
        } catch (IOException e) {
            //TODO auto-generated catch block
            e.printstacktrace ();
        }
    }
method Four

public void WriteStringToFile4 (String filePath) {
        try {
            Randomaccessfile rf = new Randomaccessfile (FilePath, " RW ");
            Rf.writebytes ("op\r\n");
            Rf.writebytes ("app\r\n");
            Rf.writebytes ("hijklllll");
            Rf.close ();
        } catch (IOException e) {
            e.printstacktrace ();
        }
    }
Method Five

public void WriteStringToFile5 (String filePath) {
        try {
            FileOutputStream fos = new FileOutputStream (FilePath); c2/>string s = "Http://www.jb51.netl";
            Fos.write (S.getbytes ());
            Fos.close ();
        } catch (Exception e) {
            //TODO auto-generated catch block
            e.printstacktrace ();
        }
    }
read the contents of the file to a string
Method One

/** * reads files in bytes and is often used to read binary files, such as pictures, sounds, images, and so on.

* Of course, it can also read strings. * * * seems to say that the network environment is more complex, each pass over the characters are fixed long, in this way. */Public String readString1 () {try {//fileinputstream) is used to read raw byte streams such as image data. 

            To read character streams, consider using FileReader.

            FileInputStream Instream=this.openfileinput (file_name);

            Bytearrayoutputstream BOS = new Bytearrayoutputstream ();

            Byte[] Buffer=new byte[1024];

            int length=-1;

                while (length = instream.read (buffer)!=-1) {bos.write (buffer,0,length);

                The interpretation of the Write method SDK is writes count bytes from the byte array buffer starting at the offset index to this stream.

            When the stream closes the contents still exist} bos.close ();

            Instream.close ();   

            return bos.tostring (); Why not take out the size of the buffer at a lump-sum. Why are you writing to the BOS?

            return new (buffer, "UTF-8") not better?       
return new String (Bos.tobytearray (), "UTF-8");
        }

    } 
Method Two

Someone said FileReader  read the string better, then use the FileReader bar

    //read one at a time is not a bit inefficient.

    private static String readString2 ()

    {

        stringbuffer str=new stringbuffer ("");

        File File=new file (file_in);

        try {

            FileReader fr=new filereader (file);

            int ch = 0;

            while (ch = fr.read ())!=-1)

            {

                System.out.print ((char) ch+ ""); 

            }

            Fr.close ();

        } catch (IOException e) {

            //TODO auto-generated catch block

            e.printstacktrace ();

            System.out.println ("File reader Error");

        }

        return str.tostring ();

    }
Method Three

/* Read strings by byte/////////////////////////////////////

    Str= "";

    File File=new file (file_in);

    try {

        FileInputStream in=new fileinputstream (file);

        Size  is the length of the string, and here is a one-time read

        int size=in.available ();

        Byte[] Buffer=new byte[size];

        In.read (buffer);

        In.close ();

        Str=new String (buffer, "GB2312");

    } catch (IOException e) {

        //TODO auto-generated catch block return

        null;

        E.printstacktrace ();

    }

    return str;

}
method Four

/*inputstreamreader+bufferedreader reads a string, the InputStreamReader class is a bridge from bytes to character streams////* Read the formatted data to be processed is a good way to read it/* privat

        e static String ReadString4 () {int len=0;

        StringBuffer str=new StringBuffer ("");

        File File=new file (file_in);

            try {fileinputstream is=new fileinputstream (file);

            InputStreamReader isr= New InputStreamReader (IS);

            BufferedReader in= New BufferedReader (ISR);

            String Line=null;

                    while ((Line=in.readline ())!=null) {if (len!= 0)//handling line breaks

                Str.append ("\ r \ n" +line);

                else {str.append (line);

            } len++;

            } in.close ();

        Is.close ();

        catch (IOException e) {//TODO auto-generated catch block E.printstacktrace ();

  }      return str.tostring ();
 }

From

1, http://www.jb51.net/article/49270.htm

2, http://blog.csdn.net/stormbjm/article/details/19545941


Related Article

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.