8-1 写入日志文件 (0 分)
 

编写程序,要求:用户在键盘每输入一行文本,程序将这段文本显示在控制台中。当用户输入的一行文本是“exit”(不区分大小写)时,程序将用户所有输入的文本都写入到文件log.txt中,并退出。(要求:控制台输入通过流封装System.in获取,不要使用Scanner)

import java.io.*;

public class Main
{
public static void main(String[] args)
{
BufferedReader br = null;
BufferedWriter bw = null;
try {
br = new BufferedReader(new InputStreamReader(System.in));
bw = new BufferedWriter(new FileWriter(new File("log.txt")));
String s;
while(!(s = br.readLine()).equalsIgnoreCase("exit"))
{
System.out.print(s);
bw.write(s);
bw.newLine();
}
}catch(IOException e) {
e.printStackTrace();
} finally {
try {
if(br != null)
{
br.close();
}
if(bw != null)
{
bw.close();
}
}catch(IOException e) {
e.printStackTrace();
}
}
}
}
8-2 文件和目录输出 (20 分)
 

查看File类的API文档,使用该类实现一个类FileList,它提供两个静态方法:1)readContentsInDirectory(String path):能够将输入参数path所指定的本地磁盘路径下的所有目录和文件的名称打印出来;2)readContentsInDirectoryRecursive(String path):能够将输入参数path所指定的本地磁盘路径下的所有目录(包含所有子孙目录)和文件的名称以层次化结构打印出来。程序的输出如下所示。

import java.io.*;
import java.util.*;
public class Main
{
public static void main(String[] args)
{
Scanner s = new Scanner(System.in);
String path = s.nextLine();
File f = new File(path);
int level = 0;
FileList fl = new FileList();
fl.readContentsInDirectory(f);
System.out.println("------------------");
fl.readContentsInDirectoryRecursive(f, level);
s.close();
}
}
class FileList
{
public void readContentsInDirectory(File path)
{
if(!path.exists())
{
System.out.println("路径"+path.getPath()+"不存在");
return ;
}
else
{
File[] f = path.listFiles();
for(int i = 0 ; i < f.length ; i++)
{
if(f[i].isFile())
{
System.out.println("[文件]"+f[i].getName());
}
else
{
System.out.println("[目录]"+f[i].getName());
}
}
}
}
public void readContentsInDirectoryRecursive(File path,int level)
{
if(!path.exists())
{
System.out.println("路径"+path.getPath()+"不存在");
return ;
}
else
{
File[] f = path.listFiles();
for(int i = 0 ; i < f.length ; i++)
{
for(int j = 0; j < level ; j++)
{
System.out.print("-");
}
if(f[i].isFile())
{
System.out.println("[文件]"+f[i].getName());
}
else
{
System.out.println("[目录]"+f[i].getName());
readContentsInDirectoryRecursive(f[i],level+2);
}
}
}
}
}
8-3 菜单文件处理 (20 分)
 

假设某个餐馆平时使用:1)文本文件(orders.txt)记录顾客的点菜信息,每桌顾客的点菜记录占一行。每行顾客点菜信息的记录格式是“菜名:数量,菜名:数量,…菜名:数量”。例如:“烤鸭:1,土豆丝:2,烤鱼:1”。2)文本文件(dishes.txt)记录每种菜的具体价格,每种菜及其价格占一行,记录格式为“菜名:价格“。例如:“烤鸭:169”。编写一个程序,能够计算出orders.txt中所有顾客消费的总价格。(注意,请使用文本读写流,及缓冲流来处理文件)

import java.util.*;
import java.io.*;
public class Main
{
public static void main(String[] args)
{
Scanner s = new Scanner(System.in);
BufferedReader br1 = null;
BufferedReader br2 = null;
List<Order> order = new ArrayList<>();
Map<String , Dish> dish = new HashMap<>();
try {
File f1 = new File("order.txt");
f1.createNewFile();
File f2 = new File("dishes.txt");
f2.createNewFile();
br1 = new BufferedReader(new FileReader("order.txt"));
br2 = new BufferedReader(new FileReader("dishes.txt"));
String S1 ;
while((S1 = br1.readLine()) != null)
{
String[] s1 = S1.split(",");
for(int i = 0 ; i < s1.length ; i++)
{
order.add(new Order(s1[0],Integer.parseInt(s1[1])));
}
}
String S2;
while((S2 = br2.readLine()) != null)
{
String[] s2 = S2.split(":");
dish.put(s2[0], new Dish(s2[0],Double.parseDouble(s2[1])));
}
double sum = 0;
for(int i = 0 ; i < order.size() ; i++)
{
sum += order.get(i).num * dish.get(i).price;
}
System.out.println(sum);
}catch(Exception e) {
e.printStackTrace();
}
finally {
try {
if(br1 != null)
{
br1.close();
}
if(br2 != null)
{
br2.close();
}
}catch(Exception e) {
e.printStackTrace();
}
}
s.close();
}
}
class Order
{
public String name;
public int num;
public Order(String name, int num)
{
this.name = name;
this.num = num;
}
}
class Dish
{
public String name;
public double price;
public Dish(String name, double price)
{
this.name = name;
this.price = price;
}
}
8-4 成绩文件处理 (20 分)
 

设计学生类Student,属性:学号(整型);姓名(字符串),选修课程(名称)及课程成绩(整型)。编写一个控制台程序,能够实现Student信息的保存、读取。具体要求:(1)提供Student信息的保存功能:通过控制台输入若干个学生的学号、姓名以及每个学生所修课程的课程名和成绩,将其信息保存到data.dat中;(2)数据读取显示:能够从data.dat文件中读取学生及其课程成绩并显示于控制台。(要求,学号和课程成绩按照整数形式(而非字符串形式)存储)

import java.io.*;
import java.util.*; public class Test4 { public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String l = null;
DataInputStream dis = null;
DataOutputStream dos = null;
try {
dos = new DataOutputStream(new FileOutputStream("data.dat"));
while(!(l=sc.nextLine()).equals("exit")) {
String[] ss = l.split(" ");
Student s = new Student(Integer.parseInt(ss[0])
,ss[1],ss[2],Integer.parseInt(ss[3])); byte[] bs = s.getNameBytes();
byte[] cs = s.getCourseBytes(); dos.writeInt(s.no);
dos.writeInt(bs.length);
dos.write(bs);
dos.writeInt(cs.length);
dos.write(cs);
dos.writeInt(s.score);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
dos.close();
}catch (IOException e) {
e.printStackTrace();
}
} try {
File f = new File("data.dat");
int size = (int) f.length();
int records = size/(4+4+(96+240)/8);
dis = new DataInputStream(new FileInputStream("data.dat")); while (true) {//for (int i=0;i<records;i++) {
int no = dis.readInt();
int bsize = dis.readInt();
byte[] bs = new byte[bsize];
dis.read(bs);
String name = new String(bs);
int wsize = dis.readInt();
byte[] ws = new byte[wsize];
dis.read(ws);
String course = new String(ws);
int score = dis.readInt();
System.out.println(no+" "+name+" "+course+" "+score);
}
} catch (EOFException e) {
System.out.println("end of file");
} catch (IOException e){
e.printStackTrace();
}finally {
try {
dis.close();
}catch (IOException e) {
e.printStackTrace();
}
}
} } class Student {
int no;
String name;
String course;
int score; public byte[] getNameBytes() {
byte[] src = name.getBytes();
return src;
} public byte[] getCourseBytes(){
byte[] src = course.getBytes();
return src;
} public Student(int no, String name, String course, int score) {
super();
this.no = no;
this.name = name;
this.course = course;
this.score = score;
} }
8-5 图书馆持久化 (20 分)
 

构造图书类,包含名称(字符串)、作者(字符串)、出版社(字符串)、版本号(整数)、价格(浮点数),构造图书馆类,其中包含若干图书,用容器存储图书对象,然后定义方法void addBook(Book b)添加图书对象,定义方法void persist(),将所有图书存至本地文件books.dat里,定义方法Book[] restore() 从文件books,dat中读取所有图书,并返回图书列表数组。 main函数中构造图书馆类对象,向其中添加3个图书对象,测试其persist和restore方法。(注意,请使用对象序列化方法实现)

import java.io.*;
import java.util.ArrayList;
import java.util.List; public class Test5 {
/*构造图书类,包含名称(字符串)、作者(字符串)、出版社(字符串)、版本号(整数)、价格(浮点数),
* 构造图书馆类,其中包含若干图书,用容器存储图书对象,
* 然后定义方法void addBook(Book b)添加图书对象,
* 定义方法void persist(),将所有图书存至本地文件books.dat里,
* 定义方法Book[] restore() 从文件books,dat中读取所有图书,并返回图书列表数组。
* main函数中构造图书馆类对象,向其中添加3个图书对象,测试其persist和restore方法。
* (注意,请使用对象序列化方法实现)
*/ public static void main(String[] args) {
ObjectOutputStream oos = null;
Book[] bs = {
new Book ("Java","张峰", "清华大学出版社",2, 23.5),
new Book ("C++","刘冰", "清华大学出版社",2, 18),
new Book ("C","王莉", "清华大学出版社",2, 35)
};
Library l = new Library();
for (Book b : bs) {
l.addBook(b);
}
l.persist();
Book[] bs2 = l.restore();
for (Book b : bs) {
System.out.println(b);
}
} } class Book implements Serializable{
String name;
String author;
String press;
int edition;
double price; public Book(String name, String author, String press, int edition, double price) {
super();
this.name = name;
this.author = author;
this.press = press;
this.edition = edition;
this.price = price;
} @Override
public String toString() {
return "Book [name=" + name + ", author=" + author + ", press=" + press + ", edition=" + edition + ", price="
+ price + "]";
}
} class Library
{
List<Book> bs = new ArrayList<Book>(); public void addBook(Book b)
{
bs.add(b);
} public void persist ()
{
ObjectOutputStream oos = null;
try {
oos = new ObjectOutputStream(
new FileOutputStream("books.dat"));
// 将per对象写入输出流
for(Book b :bs)
oos.writeObject(b);
}
catch (IOException ex)
{
ex.printStackTrace();
} finally {
try {
if (oos!=null)
oos.close();
} catch (Exception e) {
e.printStackTrace();
}
}
} public Book[] restore()
{
ObjectInputStream ois = null;
bs = new ArrayList<Book>();
try {
ois = new ObjectInputStream(
new FileInputStream("books.dat"));
//从输入流中读取一个Java对象,并将其强制类型转换为Person类
while (true)
{
Book b = (Book)ois.readObject();
bs.add(b);
}
}catch (EOFException e){
System.out.println("end of file");
}catch (Exception e){
e.printStackTrace();
}finally {
try {
if (ois!=null)
ois.close();
} catch (Exception e) {
e.printStackTrace();
}
}
Book[] ba = new Book[bs.size()];
bs.toArray(ba);
return ba;
} }
8-6 按行读文件 (20 分)
 

使用java的输入/输出流技术将一个文本文件的内容按行读出,每读出一行就顺序添加行号,并写入到另一个文件中。

import java.io.*;
public class Main
{
public static void main(String[] args)
{
BufferedReader br = null;
BufferedWriter bw = null;
try {
br = new BufferedReader(new FileReader("in.txt"));
bw = new BufferedWriter(new FileWriter("out.txt"));
String s;
for(int i = 0 ; (s = br.readLine())!=null ; i++)
{
bw.write(i+" , "+s);
bw.newLine();
}
}catch(Exception e) {
e.printStackTrace();
}
finally {
try {
if(br != null)
{
br.close();
}
if(bw != null)
{
bw.close();
}
}catch(Exception e) {
e.printStackTrace();
}
}
}
}
8-7 读写文件--程序设计 (20 分)
 

编写一个程序实现如下功能,文件fin.txt是无行结构(无换行符)的汉语文件,从fin中读取字符,写入文件fou.txt中,每40个字符一行(最后一行可能少于40个字) 请将程序代码贴到答案区内

import java.io.*;
public class Main
{
public static void main(String[] args)
{
BufferedReader br = null;
BufferedWriter bw = null;
try {
br = new BufferedReader(new FileReader("fin.txt"));
bw = new BufferedWriter(new FileWriter("out.txt"));
char[] c = new char[40];
int len = 40;
while((br.read(c, 0, len) )!= -1)
{
bw.write(c, 0, len);
bw.newLine();
}
}catch(Exception e) {
e.printStackTrace();
}
finally {
try {
if(br != null)
{
br.close();
}
if(bw != null)
{
bw.close();
}
}catch(Exception e) {
e.printStackTrace();
}
}
}
}

IO题目的更多相关文章

  1. 普及C组第四题(8.2)

    1342. [南海2009初中]cowtract(网络) (Standard IO) 题目:  Bessie受雇来到John的农场帮他们建立internet网络.农场有 N (2<= N < ...

  2. 普及C组第二题(8.2)

    1340. [南海2009初中]jumpcow(牛跳) (Standard IO) 题目: John的奶牛们计划要跳到月亮上去.它们请魔法师配制了 P (1 <= P <=150,000) ...

  3. NepCTF pwn writeup

    上周抽时间打了nepnep举办的CTF比赛,pwn题目出的挺不错的,适合我这种只会一点点选手做,都可以学到新东西. [签到] 送你一朵小红花 64位程序,保护全开. 程序会在buf[2]处留下一个da ...

  4. VS2015编译GEOS

    下载链接:http://trac.osgeo.org/geos/ 1. 打开cmake,加载geos源码和定位geos的工程存放位置: 2.点击configure,会报错,首先设置CMAKE_INST ...

  5. Linux硬件IO的优化简介

    Linux硬件IO的优化简介 首先简单介绍下有哪些硬件设备如下(由于硬件种类厂家等各种因素我就不在此多做介绍有兴趣的可以自行学习): 1.CPU:中央处理器,是计算机运算控制的核心部件之一,相当于人的 ...

  6. MMAP和DIRECT IO区别

    看完此文,题目不言自明.转自 http://blog.chinaunix.net/uid-27105712-id-3270102.html 在Linux 开发中,有几个关系到性能的东西,技术人员非常关 ...

  7. 看看国外的javascript题目,你能全部做对吗?

    叶小钗 的博客最近都在讨论面试题目 正好以前也看过一篇,就借花献佛拿出来分享一下 http://perfectionkills.com/javascript-quiz/ 附带了自己的理解,答案有争议的 ...

  8. PHP面试题目搜集

    搜集这些题目是想在学习PHP方面知识有更感性的认识,单纯看书的话会很容易看后就忘记. 曾经看过数据结构.设计模式.HTTP等方面的书籍,但是基本看完后就是看完了,没有然后了,随着时间的推移,也就渐渐忘 ...

  9. 经典.net面试题目

    1. 简述 private. protected. public. internal 修饰符的访问权限. 答 . private :   私有成员, 在类的内部才可以访问. protected : 保 ...

  10. 二十一、Java基础--------IO流之综合案例分析

    前三篇文章详细介绍了IO流体系所涉及的重点内容,为了帮助理解与学习,本片博客主要是分析一个与IO操作相关的题目. 例1:在我们观看视频时经常要关注的就是视频的时间长度,在学习了IO操作之后,就可以自己 ...

随机推荐

  1. mybatis核心配置文件—mappers标签设置映射文件

    <!-- 加载映射文件 --> <mappers> <!--<mapper resource="mappers/UserMapper.xml"& ...

  2. es6数组去重、数组中的对象去重 && 删除数组(按条件或指定具体元素 如:id)&& 筛选去掉没有子组件的父组件

    // 数组去重 { const arr = [1,2,3,4,1,23,5,2,3,5,6,7,8,undefined,null,null,undefined,true,false,true,'中文' ...

  3. 每日一抄 Go语言聊天服务器

    server.go package main import ( "bufio" "fmt" "log" "net" ) ...

  4. vagrant用密码连接ssh

    1通过 ssh address连接 1:进去linux 2:修改配置文件信息 vi /etc/ssh/sshd_config 修改 passwordAuthentication no 改为 passw ...

  5. com.alibaba.fastjson.JSONObject cannot be cast to xxx

    今天在使用json格式的数据进行转化的时候遇到了这个问题,故此记录下来. 通常我们使用JSON把数据转成实体的方法是这样的 List<DataModel> dataModels= (Lis ...

  6. 基于rabbitmq之MQTT协议的智能家居

    智能家居项目 智能可燃气体报警器 产品是一款可燃气体报警器,如果家中燃气泄露浓度到达一定阈值,报警器检测到并上传气体浓度值给后台,后台以电话.短信.微信等方式,提醒用户家中可能有气体泄漏. 用户还可能 ...

  7. 简述ECMAScript6的新特性

    1.增加块级作用域 2.增加let const 3.解构赋值 4.函数参数拓展(函数参数可以使用默认值,不定参数及拓展参数) 5.增加class类支持 6.增加箭头函数 7.增加模块和模块加载(ES6 ...

  8. XSS跨站脚本攻击(Cross Site Scripting)

    XSS是跨站脚本攻击(Cross Site Scripting),不写为CSS是为了避免和层叠样式表(Cascading Style Sheets)的缩写混淆,所以将跨站脚本攻击写为XSS. 攻击者可 ...

  9. Java 中的内存分配

    Java 中的内存分配 Java 程序运行时,需要在内存中分配空间.为了提高运算效率,就对空间进行了不同区域的划分,因为每一片区域都有特定的处理数据方式和内存管理方式. 一.栈:储存局部变量 局部变量 ...

  10. unable to access 'http://*****/': The requested URL returned error: 414

    git拉取gitlab项目: unable to access 'http://git.yijiago.com/meimeng/lsyjg_java.git/': The requested URL ...