Java read/write TXT file

Source: Internet
Author: User

Java reads the contents of the TXT file. Can be understood as follows:

1, first get a file handle. File File = new file (); File is a handle to the document. There was a network of calls between the two of them. Then you can start making a phone call.

2, through this line to read the information of party A: new FileInputStream (file) At present this information has been read in memory. Then it needs to be interpreted as something that B can understand.

3, since you have used FileInputStream (). Then the corresponding need to use InputStreamReader () This method to interpret the memory just loaded in the data

4, after the completion of interpretation to output AH. Of course it's going to be converted into data that the IO can recognize. Then you need to call the byte code read Method BufferedReader (). Use the ReadLine () method of BufferedReader () to read each row of data in the TXT file.

/////////////////////////////////////////////////////////////////////

Method One, simple use of scanner and printwriter//////

////////////////////////////////////////////////////////////////////

Package Com.stone.demo;

Import Java.io.File;
Import java.io.FileNotFoundException;
Import Java.io.PrintWriter;
Import Java.util.Scanner;

public class Readandwritetxtbyscanner {

private static void Readtxtfile (String filepath) {
try {
Scanner in=new Scanner (New File (filepath));
while (In.hasnext ()) {
String Str=in.nextline ();
System.out.println (str);
}
} catch (FileNotFoundException e) {
E.printstacktrace ();
}
}

private static void Writetxtfile (String filepath) {
try {
@SuppressWarnings ("resource")
String relativepath=system.getproperty ("User.dir") + "/src/com/stone/demo/writefile.txt";
PrintWriter out=new PrintWriter (relativepath);
Out.write ("12312");
Out.write ("\ n");
Out.write ("12312");
Out.flush ();
Out.close ();
} catch (Exception e) {
E.printstacktrace ();
}
}

public static void Main (string[] args) {
String filepath=system.getproperty ("User.dir") + "/src/com/stone/demo/writefile.txt";
Writetxtfile (filepath);
System.out.println ("==================");
Readtxtfile (filepath);
}
}

/////////////////////////////////////////////////////

Method two: Using IO stream///////////////////

/////////////////////////////////////////////////////

  1. Package Com.stone.demo;
  2. Import Java.io.BufferedReader;
  3. Import Java.io.BufferedWriter;
  4. Import Java.io.File;
  5. Import Java.io.FileInputStream;
  6. Import java.io.FileNotFoundException;
  7. Import Java.io.FileWriter;
  8. Import java.io.IOException;
  9. Import Java.io.InputStreamReader;
  10. Import Java.util.Scanner;
  11. Public class Readandwritetxtbyfile {
  12. /** 
  13. * Function: Java read the content of TXT file steps:
  14. * 1: Get the file handle first
  15. * 2: Get the file handle as input a byte stream, need to read this input stream
  16. * 3: After reading to the input stream, the generated byte stream needs to be read
  17. * 4: The output of one row. ReadLine (). Note: It is unusual to consider the situation
  18. * @param FilePath
  19. */
  20. public static void Readtxtfile (String filePath) {
  21. try {
  22. String encoding = "GBK";
  23. File File = new file (FilePath);
  24. if (file.isfile () && file.exists ()) { //Determine if the file exists
  25. InputStreamReader Read = new InputStreamReader (new FileInputStream (file), encoding); Considering the encoding format
  26. BufferedReader BufferedReader = new BufferedReader (read);
  27. String linetxt = null;
  28. While ((Linetxt = Bufferedreader.readline ()) = null) {
  29. System.out.println (Linetxt);
  30. }
  31. Read.close ();
  32. }
  33. } catch (Exception e) {
  34. SYSTEM.OUT.PRINTLN ("Error reading file contents");
  35. E.printstacktrace ();
  36. }
  37. }
  38. private static void Writetxtfile (String filepath) {
  39. File file=new file (filepath);
  40. BufferedWriter writer = null;
  41. try {
  42. if (File.isfile () &&!file.exists ()) {
  43. System.out.println ("The specified file cannot be found");
  44. File.createnewfile (); //Does not exist then create
  45. }
  46. else{
  47. //writer = new BufferedWriter (new FileWriter (file,true));//Add true here to not overwrite the contents of the original TXT file to continue writing
  48. writer = New BufferedWriter (new FileWriter (file));
  49. Writer.write ("Hello");
  50. Writer.write ("\ n");
  51. Writer.write ("Hello");
  52. }
  53. } catch (Exception e) {
  54. E.printstacktrace ();
  55. } finally {
  56. if (writer! = null) {
  57. try {
  58. Writer.flush ();
  59. Writer.close ();
  60. } catch (IOException e) {
  61. E.printstacktrace ();
  62. }
  63. }
  64. }
  65. }
  66. public static void Main (String argv[]) {
  67. String Filepath=system.getproperty ("User.dir") +"/src/com/stone/demo/txtfile.txt";
  68. Writetxtfile (filepath);
  69. System.out.println ("===================");
  70. Readtxtfile (filepath);
  71. }
  72. }

Note: Excerpt from http://blog.csdn.net/giserstone/article/details/40922189

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.