实验九输入输出流
1.实验目的
1、掌握字符输入、输出流的用法
2、掌握使用Scanner类解析文件
3、掌握Console流的使用
2.实验内容
1、根据附录里的源代码,按照注释要求,完成代码填空,使程序能够运行
得出结果。
1) 实验1举重成绩单
2) 实验2统计英文单词
3) 实验3密码流
4) 实验4学读汉字
5)实验5 读取Zip文件
2、设计编写程序完成以下任务。
1)修改实验2,要求按字典顺序输出全部不相同的单词。
2)参考实验3编写一个程序,程序运行时,要求用户输入的密码是:hello。如果用户输入了正确的密码。程序将输出“你好,欢迎你!”。程序允许用户2次输入的密码不正确,一旦超过2次,程序将立刻退出。
3)在本机的磁盘系统中,找一个文件夹,利用File类的提供方法,列出该文件夹中的所有文件的文件名和文件的路径,执行效果如下:路径是xxx的文件夹内的文件有:
文件名:abc.txt
路径名:c:\temp\abc.txt
--------------------------------------------
文件名:def.txt
路径名:c:\temp\def.txt
知识点:File管理
4)使用java的输入输出流将一个文本文件的内容读出并在控制台将文件中的内容打印出来。(参考书上P289页)
5)从控制台输入一串字符串,将该串字符串写入到磁盘某位置上的out.txt文件中去。(参考教材P290页)
6)使用java的输入输出流将一个文本文件的内容按行读取,每读一行就顺序添加行号,并写入到另一个文件中.
7)定义一个Person类,包含姓名、年龄、身份证号码属性。有一个带参数的构造方法用于对所有属性赋值,还有一个study的方法,里面只打印一条“我喜欢学习”的话。写一个Test类,里面实例化若干个Person对象,并将这些对象写入到obj.txt文件中去。
8)创建c:/test.txt文件并在其中输入"hello world"
创建一个输入流读取该文件中的文本
并且把小写的l变成大写L再利用输出流写入到d:\test.txt中
实现步骤:(1)在本地硬盘C盘下创建一个文件test.txt
(2)创建一个包含main()方法的类,并在main中编写代码
(3)运行代码并且测试结果
实现过滤器的功能
效果显示:
知识点:IO字符流、String常用方法
3.实验步骤
略
4.评分标准
1.A——内容功能完善,编程风格好,人机接口界面好;
2.B——内容功能完善,编程风格良好,人机接口界面良好;
3.C——完成必做内容;
4.D——能完成必做内容;
5.E——未按时完成必做内容,或者抄袭(雷同者全部为E).
参照书上实验按模版要求,将【代码】替换为Java程序代码,编写好完整的程序文档,最后运行得到的相关文件,把实验所得文件一起打包上交。(压缩包的文件名为:学号后三位和名字开头字母,如109zhh.RAR|ZIP)
附录:
实验1 举重成绩单
1.模板代码
AnalysisResult.java
import java.io.*;
import java.util.*;
public class AnalysisResult {
public static void main(String[] args) {
try{
File fRead=new File("d:\\score.txt");
File fWrite=new File("d:\\scoreAnalysis.txt");
Writer out=//【代码1】//以尾加方式创建指向文件fWrite的out流
BufferedWriter bufferWrite=//【代码2】//创建指向out的bufferWrite流
Reader in=//【代码3】//创建指向文件fRead的in流
BufferedReader bufferRead=//【代码4】//创建指向in的bufferRead流
String str=null;
while((str=bufferRead.readLine())!=null){
double totalScore=Fenxi.getTotalScore(str);
str=str+"总成绩:"+totalScore;
System.out.println(str);
bufferWrite.write(str);
bufferWrite.newLine();
}
bufferRead.close();
bufferWrite.close();
}
catch(FileNotFoundException e){
System.out.println(e.toString());
}
catch(IOException e){
System.out.println(e.toString());
}
}
}
Fenxi.java
import java.util.regex.*;
public class Fenxi {
public static double getTotalScore(String s){
String regex="\\d{1,5}";
double totalScore=0.0;
Pattern p = http://www.wendangku.net/doc/ef7865a92af90242a895e5fe.htmlpile(regex);
Matcher m = p.matcher(s);
while(m.find()) {
try{
totalScore=totalScore+Double.parseDouble(m.group());
}
catch(NumberFormatException e){
System.out.println(e.getMessage());
}
}
return totalScore;
}
}
实验2 统计英文单词字
1.模板代码
WordStatistic.java
import java.io.*;
import java.util.Scanner;
import java.util.Vector;
public class WordStatistic
{
Vector
File file=new File("d:\\english.txt");
Scanner sc=null;
String regex;
WordStatistic()
{
allWord=new Vector
noSameWord=new Vector
regex="[\\s\\d\\p{Punct}]+";
try{
sc=//【代码1】//创建指向file的sc
//【代码2】//sc调用useDelimiter(String regex)方法,向参数传递regex }catch(IOException exp){
System.out.println(exp.toString());
}
}
void setFileName(String name){
file=new File(name);
try{
sc=new Scanner(file);
http://www.wendangku.net/doc/ef7865a92af90242a895e5fe.htmleDelimiter(regex);
}catch(IOException exp){
System.out.println(exp.toString());
}
}
public void wordStatistic()
{
try{
while(sc.hasNext()){
String word=sc.next();
allWord.add(word);
if(!noSameWord.contains(word)){
noSameWord.add(word);
}
}
}catch(Exception e){}
}
public Vector
{ return allWord;
}
public Vector
{ return noSameWord;
}
}
OutputWordMess.java
import java.util.*;
public class OutputWordMess {
public static void main(String args[]){
Vector
WordStatistic statistic=new WordStatistic();
statistic.setFileName("d:\\hello.txt");
//【代码3】//statistic调用wordStatistic方法
allWord=statistic.getAllWord();
noSameWord=statistic.getNoSameWord();
System.out.println("共有"+allWord.size()+"个英文单词");
System.out.println("有"+noSameWord.size()+"个互不相同英文单词");
System.out.println("按出现频率排列:");
int count[]=new int[noSameWord.size()];
for(int i=0;i String s1=noSameWord.elementAt(i); for(int j=0;j String s2=allWord.elementAt(j); if(s1.equals(s2)){ count[i]++; } } } for(int m=0;m for(int n=m+1;n if(count[n]>count[m]){ String temp=noSameWord.elementAt(m); noSameWord.setElementAt(noSameWord.elementAt(n),m); noSameWord.setElementAt(temp,n); int t=count[m]; count[m]=count[n]; count[n]=t; } } } for(int m=0;m double frequency=(1.0*count[m])/allWord.size(); System.out.printf("%s:%-7.3f",noSameWord.elementAt(m),frequency); } } } 实验3 密码流 1.模板代码 PassWord.java import java.io.*; public class PassWord { public static void main(String[] args) { boolean success=false; int count=0; Console cons; char[] passwd; cons=System.console(); while(true){ System.out.print("输入密码:"); passwd=cons.readPassword(); count++; String password= new String(passwd); if(password.equals("tiger123")){ success=true; System.out.println("您第"+count+"次输入的密码正确!"); break; }else{ System.out.println("您第"+count+"次输入的密码"+password+"不正确!"); } if(count==3){ System.out.println("您"+count+"次输入的密码都不正确!"); System.exit(0); } } if(success){ try{ File file=new File("D:\\score.txt"); FileReader inOne=new FileReader(file); BufferedReader inTow=new BufferedReader(inOne); String s=null; while((s=inTow.readLine())!=null){ System.out.println(s); } inOne.close(); inTow.close(); }catch(FileNotFoundException fe){ System.out.println(fe.toString()); } catch(IOException ioe){ System.out.println(ioe.toString()); } } } } 实验4 学读汉字 1.模板代码 ChineseCharacters.java import java.io.*; import java.util.StringTokenizer; public class ChineseCharacters { public StringBuffer getChinesecharacters(File file) { StringBuffer hanzi=new StringBuffer(); try{ FileReader inOne=【代码1】 //创建指向文件f的inOne 的对象 BufferedReader inTwo=【代码2】 //创建指向文件inOne的inTwo 的对象 String s=null; int i=0; while((s=【代码3】)!=null) //inTwo读取一行 { StringTokenizer tokenizer=new StringTokenizer(s," ,'\n' "); while(tokenizer.hasMoreTokens()) { hanzi.append(tokenizer.nextToken()); } } } catch(Exception e) {} return hanzi; } } StudyFrame.java import java.awt.*; import java.awt.event.*; import java.io.*; import javax.sound.sampled.*; public class StudyFrame extends Frame implements ItemListener,ActionListener,Runnable { ChineseCharacters chinese; Choice choice; Button getCharacters,voiceCharacters; Label showCharacters; StringBuffer trainedChinese=null; Clip clip=null; Thread voiceThread; int k=0; Panel pCenter; CardLayout mycard; TextArea textHelp; MenuBar menubar; Menu menu; MenuItem help; public StudyFrame() { chinese=new ChineseCharacters(); choice=new Choice(); choice.add("training1.txt"); choice.add("training2.txt"); choice.add("training3.txt"); showCharacters=new Label("",Label.CENTER); showCharacters.setFont(new Font("宋体",Font.BOLD,72)); showCharacters.setBackground(Color.green); getCharacters=new Button("下一个汉字"); voiceCharacters=new Button("发音"); voiceThread=new Thread(this); choice.addItemListener(this); voiceCharacters.addActionListener(this); getCharacters.addActionListener(this); Panel pNorth=new Panel(); pNorth.add(new Label("选择一个汉字字符组成的文件")); pNorth.add(choice); add(pNorth,BorderLayout.NORTH); Panel pSouth=new Panel(); pSouth.add(getCharacters); pSouth.add(voiceCharacters); add(pSouth,BorderLayout.SOUTH); pCenter=new Panel(); mycard=new CardLayout(); pCenter.setLayout(mycard); textHelp=new TextArea(); pCenter.add("hanzi",showCharacters); pCenter.add("help",textHelp); add(pCenter,BorderLayout.CENTER); menubar=new MenuBar(); menu=new Menu("帮助"); help=new MenuItem("关于学汉字"); help.addActionListener(this); menu.add(help); menubar.add(menu); setMenuBar(menubar); setSize(350,220); setVisible(true); addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent e) { System.exit(0); } }); validate(); } public void itemStateChanged(ItemEvent e) { String fileName=choice.getSelectedItem(); File file=new File(fileName); trainedChinese=chinese.getChinesecharacters(file); k=0; mycard.show(pCenter,"hanzi") ; } public void actionPerformed(ActionEvent e) { if(e.getSource()==getCharacters) { if(trainedChinese!=null) { char c=trainedChinese.charAt(k); k++; if(k>=trainedChinese.length()) k=0; showCharacters.setText(""+c); } else { showCharacters.setText("请选择一个汉字字符文件"); } } if(e.getSource()==voiceCharacters) { if(!(voiceThread.isAlive())) { voiceThread=new Thread(this); } try{ voiceThread.start(); } catch(Exception exp){} } if(e.getSource()==help) { mycard.show(pCenter,"help") ; try{ File helpFile=new File("help.txt"); FileReader inOne=【代码4】 //创建指向文件helpFile的inOne 的对象 BufferedReader inTwo=【代码5】 //创建指向文件inOne的inTwo 的对象 String s=null; while((s=inTwo.readLine())!=null) { textHelp.append(s+"\n"); } inOne.close(); inTwo.close(); } catch(IOException exp){} } } public void run() { voiceCharacters.setEnabled(false); try{ if(clip!=null) { clip.close() } clip=AudioSystem.getClip(); File voiceFile=new File(showCharacters.getText().trim()+".wav"); clip.open(AudioSystem.getAudioInputStream(voiceFile)); } catch(Exception exp){} clip.start(); voiceCharacters.setEnabled(true); } } StudyMainClass.java public class StudyMainClass { public static void main(String args[]) { new StudyFrame(); } } 实验5 读取Zip文件 1.模板代码 ReadZipFile.java import java.io.*; import java.util.zip.*; public class ReadZipFile { public static void main(String args[]) { File f=new File("book.zip"); File dir=new File("Book"); byte b[]=new byte[100]; dir.mkdir(); try { ZipInputStream in=new ZipInputStream(new FileInputStream(f)); ZipEntry zipEntry=null; while((zipEntry=in.getNextEntry())!=null) { File file=new File(dir,zipEntry.getName()); FileOutputStream out=new FileOutputStream(file); int n=-1; System.out.println(file.getAbsolutePath()+"的内容:"); while((n=in.read(b,0,100))!=-1) { String str=new String(b,0,n); System.out.println(str); out.write(b,0,n); } out.close(); } in.close(); } catch(IOException ee) { System.out.println(ee); } }