java reads and writes the same file

Keywords: Java

The same file cannot be read or written at the same time, because the original file will be overwritten when we write the file. If so, for the same file, the file will be overwritten and cannot be read next time

Of course, for two different files, you can read and write at the same time

Title: 26 unordered letters are stored in a text. It is required to sort the letters and write them back into the file

Analysis: the read file content can be stored in a certain form in memory, and then written separately.

1. Use the collection to store the read in files

 1  public static void fileRevise(File file) throws IOException {
 2         Reader reader=new BufferedReader(new FileReader(file));
 3         //To access, as a collection, by using memory as a medium
 4         int len;
 5         char[] charArray=new char[1024];
 6         //Collection is used to store read data
 7         List<Character> list=new ArrayList<>();//char Collection of types, saving char[]Read data
 8         while ((len=reader.read(charArray))!=-1){
 9             for (int i = 0; i <len ; i++) {
10                 list.add(charArray[i]);//char->string
11             }
12         }
13         char[] newArray=new char[list.size()];
14         for (int i = 0; i <list.size() ; i++) {
15             newArray[i]=list.get(i);
16         }
17         Arrays.sort(newArray);
18         Writer write=new BufferedWriter(new FileWriter(file));
19         write.write(newArray);
20         //Closed flow
21 
22         reader.close();
23         write.close();
24     }

2. Store with string. The unique readLine() method in BufferReader can read one line at a time

 1  //The method of buffering stream with character readline()Read, use string cache, change string to character array and write again
 2     public static void fileRevise2(File file) throws IOException {
 3         Reader reader=new BufferedReader(new FileReader(file));
 4         StringBuilder sb=new StringBuilder();
 5         String str;
 6         while ((str=((BufferedReader) reader).readLine())!=null){
 7             sb.append(str);
 8         }
 9         System.out.print(sb);
10         char[] cArray=sb.toString().toCharArray();//
11         Arrays.sort(cArray);
12         reader.close();
13         Writer write=new BufferedWriter(new FileWriter(file));
14         write.write(cArray);
15         write.close();
16     }

Posted by Trekx on Tue, 24 Dec 2019 13:20:28 -0800