Although JAVA provides a variety of input and output stream methods and methods, it is not convenient for non-character data.Therefore, for the input and output of data such as int, it can only be “Eight Immortals Crossing the Sea, each showing supernatural power”.Here's a small example of writing and reading data to a file. Let's talk about the author's way. Hopefully it will help a beginner.
Problem Description:
The programming program generates 100 random numbers between 1 and 100 and writes them to a file, then reads them out of the file, sorts them, and writes them to another file.
Code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 |
Import java.io.*; Import java.util.*; Public class WriteRead { Public static void main(String[] args) { Random rd=new Random(); Int nNum[]=new int[100]; For(int i=0;i<100;i++) { nNum[i]=(int)(rd.nextDouble()*100); //Generate 100 random numbers } // Write 100 integers to a file as a character stream Try { FileWriter file=new FileWriter("first.txt"); For(int i=0;i<nNum.length;i++) { String str=String.valueOf(nNum[i])+" "; //Convert the integer into a string, and add a space after it to separate each integer File.write(str); } File.close(); } Catch(IOException e) { System.out.println(e.toString()); } // Read 100 integers from the file, sort them, and write the data to a new file Try { FileReader fr=new FileReader("first.txt"); Int[] n=new int[100]; BufferedReader buff=new BufferedReader(fr); String str=""; //Read first.Txt file data (string form), stored in str While(true) { String line=buff.readLine(); //Read one line at a time to speed up the reading If(line==null) //Deciding if reading is complete Break; Str=str+line; } Buff.close(); / / Use the StringTokenizer class to split the string str, where the separator is a space StringTokenizer st=new StringTokenizer(str); For(int i=0;st.hasMoreTokens();i++) n[i]=Integer.parseInt(st.nextToken()); //convert the decomposed string to an integer and store it in an array Arrays.sort(n); //Sort //Write to file FileWriter file=new FileWriter("second.txt"); For(int i=0;i<n.length;i++) { String s=String.valueOf(n[i])+" " File.write(s); } File.close(); } Catch(IOException e) { System.out.println(e.toString()); } } } |
This article has been printed on copyright and is protected by copyright laws. It must not be reproduced without permission.If you need to reprint, please contact the author or visit the copyright to obtain the authorization. If you feel that this article is useful to you, you can click the "Sponsoring Author" below to call the author!
Reprinted Note Source: Baiyuan's Blog>>https://wangbaiyuan.cn/en/java-inputoutput-streams-at-a-glance-2-2.html
No Comment