Java read/write TXT file

Source: Internet
Author: User

Write Java program often encountered to read such as txt or write TXT file, but because to define a lot of variables, often do not remember, every time to check, hereby tidy up, easy to use, convenient understood!

    Package edu.thu.keyword.test;Import Java.io.File;Import Java.io.InputStreamReader;Import Java.io.BufferedReader;Import Java.io.BufferedWriter;Import Java.io.FileInputStream;Import Java.io.FileWriter;PublicClassCin_txt {Staticvoid Main (String args[]) {try {Prevents file creation or read failures, catches errors with catch and prints, or can throw/* Read in TXT file */String pathname ="D:\\twitter\\13_9_6\\dataset\\en\\input.txt";Absolute path or relative path can be, here is absolute path, write file when show relative path file filename =New File (pathname);The input to read the above path. TXT file InputStreamReader reader =New InputStreamReader (New FileInputStream (filename));Create an input stream object reader BufferedReader br =New BufferedReader (reader);Create an object that turns the contents of the file into a computer-readable language String line =while (line! = null) {line = Br.readline (); //reads one row of data at a time} /* write TXT file */file Writename = new File (//relative path, if not, create a new output. TXT file writename.createnewfile (); //Create new file BufferedWriter out = new bufferedwriter (new FileWriter (Writename)); Out.write ( "I will write to the file \ r \ n"); //\ r \ n is the newline Out.flush (); //the buffer contents into the file Out.close (); //finally remember to close the file} catch (Exception e) {e.printstacktrace ();}} } 

Java read-write TXT 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.