Import java.io.*;
Class Sortchar
{
Private String str;
Private Char arraylist[];
Private BufferedReader BR; Character Stream
Private File F; Read the file
Sortchar (String s)
{
F=new File (s);
}
public void Start ()
{
if (Inputdata () ==-1)
{
Return
}
To bubble sort a character array
Sortchar ();
Turns the sorted array into a string and writes the string to the B.txt file through the stream.
OutputString ();
}
Reading a string in text by BufferedReader
Failed to read file returned-1, successfully returned 1
private int Inputdata ()
{
Try
{
Br=new BufferedReader (New FileReader (f));
Read the contents of the text
while ((Str=br.readline ())!=null)
{
Convert all letters to lowercase
Str.tolowercase ();
Arraylist=str.tochararray ();
}
}
catch (IOException E)
{
SYSTEM.OUT.PRINTLN ("Error reading file!");
E.printstacktrace ();
return-1;
}
Finally
{
Close the input stream
if (br!=null)
{
Try
{
Br.close ();
}
catch (IOException E)
{
E.printstacktrace ();
}
}
}
return 1;
}
To bubble sort a character array
private void Sortchar ()
{
Char temp=0;
for (int i=0; i<arraylist.length-1; i++)
{
for (int j=0; j<arraylist.length-i-1; j + +)
{
if (arraylist[j]>arraylist[j+1])
{
TEMP=ARRAYLIST[J];
ARRAYLIST[J]=ARRAYLIST[J+1];
Arraylist[j+1]=temp;
}
}
}
}
/*
Turns the sorted array into a string and writes the string to the B.txt file through the stream.
A. Use the string class's constructor to turn a character array into a string.
B. Write the string to the B.txt file by FileWriter.
*/
private void outputstring ()
{
BufferedWriter Bw=null;
Try
{
FileWriter FW = new FileWriter ("D:\\zy\\b.txt");
BW = new BufferedWriter (FW);
Re-write the sorted string to the file
Bw.write (New String (arraylist,0,arraylist.length));
Bw.flush ();
}
catch (IOException E)
{
E.printstacktrace ();
}
Finally
{
Close the input stream
if (bw!=null)
{
Try
{
Bw.close ();
}
catch (IOException E)
{
E.printstacktrace ();
}
}
}
}
}
Class Demo
{
public static void Main (String arsg[])
{
New Sortchar ("D:\\zy\\a.txt"). Start ();
}
}
The contents of the known file A.txt file are "Bcdeadferwplkou", * Write a program to read the contents of the file and then output to the B.txt file in a natural order. * That is, the contents of the file in B.txt should be "ABCD ..." In this order.