IO题目
编写程序,要求:用户在键盘每输入一行文本,程序将这段文本显示在控制台中。当用户输入的一行文本是“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();
}
}
}
}
查看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);
}
}
}
}
}
假设某个餐馆平时使用: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;
}
}
设计学生类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;
} }
构造图书类,包含名称(字符串)、作者(字符串)、出版社(字符串)、版本号(整数)、价格(浮点数),构造图书馆类,其中包含若干图书,用容器存储图书对象,然后定义方法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;
} }
使用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();
}
}
}
}
编写一个程序实现如下功能,文件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题目的更多相关文章
- 普及C组第四题(8.2)
1342. [南海2009初中]cowtract(网络) (Standard IO) 题目: Bessie受雇来到John的农场帮他们建立internet网络.农场有 N (2<= N < ...
- 普及C组第二题(8.2)
1340. [南海2009初中]jumpcow(牛跳) (Standard IO) 题目: John的奶牛们计划要跳到月亮上去.它们请魔法师配制了 P (1 <= P <=150,000) ...
- NepCTF pwn writeup
上周抽时间打了nepnep举办的CTF比赛,pwn题目出的挺不错的,适合我这种只会一点点选手做,都可以学到新东西. [签到] 送你一朵小红花 64位程序,保护全开. 程序会在buf[2]处留下一个da ...
- VS2015编译GEOS
下载链接:http://trac.osgeo.org/geos/ 1. 打开cmake,加载geos源码和定位geos的工程存放位置: 2.点击configure,会报错,首先设置CMAKE_INST ...
- Linux硬件IO的优化简介
Linux硬件IO的优化简介 首先简单介绍下有哪些硬件设备如下(由于硬件种类厂家等各种因素我就不在此多做介绍有兴趣的可以自行学习): 1.CPU:中央处理器,是计算机运算控制的核心部件之一,相当于人的 ...
- MMAP和DIRECT IO区别
看完此文,题目不言自明.转自 http://blog.chinaunix.net/uid-27105712-id-3270102.html 在Linux 开发中,有几个关系到性能的东西,技术人员非常关 ...
- 看看国外的javascript题目,你能全部做对吗?
叶小钗 的博客最近都在讨论面试题目 正好以前也看过一篇,就借花献佛拿出来分享一下 http://perfectionkills.com/javascript-quiz/ 附带了自己的理解,答案有争议的 ...
- PHP面试题目搜集
搜集这些题目是想在学习PHP方面知识有更感性的认识,单纯看书的话会很容易看后就忘记. 曾经看过数据结构.设计模式.HTTP等方面的书籍,但是基本看完后就是看完了,没有然后了,随着时间的推移,也就渐渐忘 ...
- 经典.net面试题目
1. 简述 private. protected. public. internal 修饰符的访问权限. 答 . private : 私有成员, 在类的内部才可以访问. protected : 保 ...
- 二十一、Java基础--------IO流之综合案例分析
前三篇文章详细介绍了IO流体系所涉及的重点内容,为了帮助理解与学习,本片博客主要是分析一个与IO操作相关的题目. 例1:在我们观看视频时经常要关注的就是视频的时间长度,在学习了IO操作之后,就可以自己 ...
随机推荐
- 递归分批次插入数据(An I/O error occurred while sending to the backend报错解决方案)
//递归插入public void add(List<Object> all, long start, long limit){ //截取 List<Object> colle ...
- Django 之 ORM1
1.ORM简介 MVC或者MVC框架中包括一个重要的部分,就是ORM,它实现了数据模型与数据库的解耦,即数据模型的设计不需要依赖于特定的数据库,通过简单的配置就可以轻松更换数据库,这极大的减轻了开发人 ...
- 无法启动iis服务器
网上的大多数教程都千篇一律,增加我寻找解决方法的难度 ,在我边气边找的努力下终于找到了解决办法. 不过还是建议先去看其他的教程,其他的不行的话再来看这个 因为工作进程未能正确初始化,因而无法启动.返回 ...
- vscode提交修改的时候报错:无法推送 refs 到远端。您可以试着运行“拉取”功能,整合您的更改
vscode提交修改的时候报错:无法推送 refs 到远端.您可以试着运行"拉取"功能,整合您的更改, git操作命令行 git pull origin yourbranch - ...
- 渗透测试工具&导航合集
#前言 表哥们一般都有自己强大的工具库,今天我也稍作整理,分享交流出来一部分 #信息收集 ####dirbuster kali自带的一款工具,fuzz很方便 ####gorailgun 一款自动化做的 ...
- 【相关杂项】stdio.h中的sprintf函数/union的作用
1.定义int sprintf(char *str, const char *format, ...) 1.paras:*str:目标字符串首指针 *format:要写入目标字符串的 ...
- ssh-add
ssh-add -l https://www.jianshu.com/p/0c6719f33fb9 添加秘钥,而不是公钥
- 如何使用C++代码实现1-100之间的素数
#include "pch.h" #include <iostream> using namespace std; int main() { cout << ...
- 2021/9/26 Leetcode 两数之和
题目:给你两个整数 a 和 b ,不使用 运算符 + 和 - ,计算并返回两整数之和. int getSum(int a, int b) { while(b != 0){ unsigne ...
- 一次讲清promise
此文章主要讲解核心思想和基本用法,想要了解更多细节全面的使用方式,请阅读官方API 这篇文章假定你具备最基本的异步编程知识,例如知道什么是回调,知道什么是链式调用,同时具备最基本的单词量,例如page ...