2019.11文件流
统计文件中字母个数排序
package zai;
import java.io.*;
import java.text.DecimalFormat;
public class FileReaderTest
{
static DecimalFormat df=new DecimalFormat("######0.00");
public static void main(String[] args) throws IOException
{
FileReader fr = null;
try
{
fr = new FileReader("d:/Harry Potter and the Sorcerer's Stone.txt");
char[] cbuf = new char[32];
char[] word= {'a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z','A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z'};
double add=0;
double[] words=new double[52];
for(int x=0;x<52;x++) {
words[x]=0;
}
int hasRead = 0;
char ar;
//int length=0;
while ((hasRead = fr.read(cbuf)) > 0 )
{
for(int in=0;in<32;in++) {
ar=cbuf[in];
for(int num=0;num<52;num++) {
if(ar==word[num]) {
words[num]++;
add++;
}
}
}
}
double xzz=0;
int max=0;
for(int num1=0;num1<52;num1++) {
max=0;
for(int num=0;num<52;num++) {
if(words[max]<words[num]) {
max=num;
}
}
System.out.println(word[max]+" "+df.format(words[max]/add*100)+"%");
words[max]=0;
}
}
catch (IOException ioe)
{
ioe.printStackTrace();
}
finally
{
//使用finally块来关闭文件输入流
if (fr != null)
{
fr.close();
}
}
}
}
统计单词个数并排序
package zai;
import java.io.*;
public class word {
public static void main(String[] args)throws IOException {
String s;
long count=0;
String[] buffer;
String[] word =new String[10000];
int[] words=new int[10000];
FileReader file=new FileReader("d:/Harry Potter and the Sorcerer's Stone.txt");
BufferedReader in=new BufferedReader(file);
boolean eof=false;
int leg=0;
while(!eof){
s=in.readLine();
if(s==null)eof=true;
else{
buffer=s.split("[^a-zA-Z]");
count+=buffer.length;
int z=0;
for(int i=0;i<buffer.length;i++) {
buffer[i]=buffer[i].toLowerCase();
z=0;
for(int x=0;x<leg;x++) {
if(buffer[i].equals(word[x])) {
words[x]++;
z=1;
}
}
if(z==0&&!buffer[i].equals("")) {
word[leg]=buffer[i];
words[leg]=1;
leg++;
}
}
}
}
int max;
for(int num1=0;num1<leg;num1++) {
max=0;//for(max=0;words[max]==-1;max++);
for(int num=0;num<leg;num++) {
if(words[max]==words[num]&&word[max].compareTo(word[num])>0) {
max=num;
}
if(words[max]<words[num]){
max=num;
}
}
System.out.println(word[max]+" "+words[max]);
words[max]=-1;
}
in.close();
}
}