JAVA实验报告(文件的输入输出流 (I/O))
实验内容
1. 键盘输入10个整数,从小到大进行排序。 2. 接收键盘输入的字符串,用FileInputStream类将字符串写入文件,用FileOutputStream类读出文件内容显示在屏幕上。 3. 将一个文本文件的内容按行读出,每读出一行就顺序加上行号,并写入到另一个文件中。
package test; import java.util.Scanner;public class test1 { public static void main(String[] args) { Scanner s = new Scanner(System.in); int temp; //对数组事先声明并创建10个空间 int[] a = new int[10]; System.out.println("请输入10个整数(输入多了没用啊!)"); //把输入的数存储为数组 for (int i = 0; i < 10; i++) { a[i] = s.nextInt(); } //排序 for (int i = 0; i < 10; i++) { for (int j = i + 1; j < 10; j++) { if (a[i] > a[j]) { temp = a[i]; a[i] = a[j]; a[j] = temp; } } } //输出结果 System.out.println("排序结果是"); for (int i = 0; i < 10; i++) { System.out.print(a[i] + " "); } } }
package test; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; public class test3 { public static void main(String[] args) { //读写文件为重要操作,最好有异常捕获 try { System.out.println("请输入:"); //打开文件 File myfile = new File("I:\java test 2\test\src\test\save.txt"); byte[] outCh = new byte[100]; int bytes = System.in.read(outCh, 0, 100); FileOutputStream Fout = new FileOutputStream(myfile); Fout.write(outCh,0,bytes); byte[] inCh = new byte[bytes]; //文件输出 System.out.println("文件输出"); FileInputStream Fin = new FileInputStream(myfile); Fin.read(inCh); System.out.println(new String(inCh)); } catch (IOException e) { System.out.println(e.toString()); } } }
package test; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.File; import java.io.FileReader; import java.io.FileWriter;public class test2 { public static void main(String[] args) { String str; int i = 1; //已经写有东西的文件read.txt File f = new File("I:\java test 2\test\src\test\read.txt"); FileReader fr; try { //打开写入文件read.txt的文件output.txt FileWriter fw = new FileWriter("I:\java test 2\test\src\test\output.txt"); BufferedWriter bw = new BufferedWriter(fw); fr = new FileReader(f); BufferedReader br = new BufferedReader(fr); while (br.ready()) { str = i + "、" + br.readLine(); System.out.println(str); //写入并换行 bw.write(str+" "); bw.flush(); i++; } } catch (Exception e) { e.printStackTrace(); } } }
上一篇:
IDEA上Java项目控制台中文乱码