JAVA进行IO流操作: 文件的输入以及输出

    科技2026-08-11  15

    文件导出:

    File file = new File("D:/beyondSparseArray.data"); FileOutputStream fileOutputStream = new FileOutputStream(file); OutputStreamWriter writer = new OutputStreamWriter(fileOutputStream, "UTF-8"); System.out.println(); //chessArr2 是一个已知的数组 for (int i = 0; i < chessArr2.length; i++) { System.out.println(); if (i == chessArr2.length - 1) { writer.append(chessArr2[i][0] + "," + chessArr2[i][1] + "," + chessArr2[i][2]); } else { writer.append(chessArr2[i][0] + "," + chessArr2[i][1] + "," + chessArr2[i][2] + ","); } } System.out.println("写入文件中~~"); writer.close(); fileOutputStream.close();

    文件读取

    System.out.println("打开文件中..."); Desktop.getDesktop().open(file); // 创建 FileReader 对象 FileInputStream fis = new FileInputStream(file); InputStreamReader reader = new InputStreamReader(fis, "UTF-8"); StringBuffer sb = new StringBuffer(); while (reader.ready()) { sb.append((char) reader.read());// 转成char加到StringBuffer对象中 } System.out.println(sb.toString()); reader.close();// 关闭读取流 fis.close();// 关闭输入流,释放系统资源 System.out.println("-----恢复成数组 sparseArrHf(3列的二维数组) "); // 2.创建对应的数组 String[] str = sb.toString().split(","); int sparseArrHf[][] = new int[str.length / 3][3]; // 给数组赋值 int i = 0; for (String s : str) { sparseArrHf[(i - (i % 3)) / 3][i % 3] = Integer.parseInt(s); i++; }
    Processed: 0.008, SQL: 10