Java read and write simple code for files

Source: Internet
Author: User

The program first writes a string to the specified file and then reads the contents of the file from another file to the screen.

The program code is as follows:

Import java.io.*;

public class ReadWrite {public

	void WriteFile () {
		String str = ' This was  a program ';//What to write
		try {
			F Ileoutputstream out = new FileOutputStream ("d:/program/readwriteshuchu.txt"); Output file path
			out.write (Str.getbytes ());
			Out.close ();
		} catch (Exception e) {
			e.printstacktrace ();
		}
	}

	public void ReadFile () {
		try {
			FileInputStream in = new FileInputStream ("d:/program/ceshi.txt");//Read file path
			byte bs[] = new byte[in.available ()];
			In.read (BS);
			System.out.println ("File content=\n" + new String (BS));
			In.close ();
		} catch (Exception e) {
			e.printstacktrace ();
		}
	}

	public static void Main (string[] args) {
		ReadWrite t = new ReadWrite ();
		T.readfile ();
		T.writefile ();
	}

After the program runs, T.writefile () outputs the contents of the Ceshi.txt under the program folder of D disk to the screen, T.writefile () creates a new file named ReadWriteshuchu.txt under the program folder in D, and will A program is written inside the file.

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.