[Java] 经典代码 java io →→→→→进入此内容的聊天室

来自 , 2019-06-30, 写在 Java, 查看 106 次.
URL http://www.code666.cn/view/63154d56
  1. package IO;
  2.  
  3. import java.io.*;
  4.  
  5. public class FileDirectoryDemo {
  6. public static void main(String[] args) {
  7. // 如果没有指定参数,则缺省为当前目录。
  8. if (args.length == 0) {
  9. args = new String[] { "." };
  10. }
  11. try {
  12. // 新建指定目录的File对象。
  13. File currentPath = new File(args[0]);
  14. // 在指定目录新建temp目录的File对象。
  15. File tempPath = new File(currentPath, "temp");
  16. // 用“tempPath”对象在指定目录下创建temp目录。
  17. tempPath.mkdir();
  18. // 在temp目录下创建两个文件。
  19. File temp1 = new File(tempPath, "temp1.txt");
  20. temp1.createNewFile();
  21. File temp2 = new File(tempPath, "temp2.txt");
  22. temp2.createNewFile();
  23.  
  24. // 递归显示指定目录的内容。
  25. System.out.println("显示指定目录的内容");
  26. listSubDir(currentPath);
  27.  
  28. // 更改文件名“temp1.txt”为“temp.txt”。
  29. File temp1new = new File(tempPath, "temp.txt");
  30. temp1.renameTo(temp1new);
  31. // 递归显示temp子目录的内容。
  32. System.out.println("更改文件名后,显示temp子目录的内容");
  33. listSubDir(tempPath);
  34.  
  35. // 删除文件“temp2.txt”。
  36. temp2.delete();
  37. // 递归显示temp子目录的内容。
  38. System.out.println("删除文件后,显示temp子目录的内容");
  39. listSubDir(tempPath);
  40. } catch (IOException e) {
  41. System.err.println("IOException");
  42. }
  43. }
  44.  
  45. // 递归显示指定目录的内容。
  46. static void listSubDir(File currentPath) {
  47. // 取得指定目录的内容列表。
  48. String[] fileNames = currentPath.list();
  49. try {
  50. for (int i = 0; i < fileNames.length; i++) {
  51. File f = new File(currentPath.getPath(), fileNames[i]);
  52. // 如果是目录,则显示目录名后,递归调用,显示子目录的内容。
  53. if (f.isDirectory()) {
  54. // 以规范的路径格式显示目录。
  55. System.out.println(f.getCanonicalPath());
  56. // 递归调用,显示子目录。
  57. listSubDir(f);
  58. }
  59. // 如果是文件,则显示文件名,不包含路径信息。
  60. else {
  61. System.out.println(f.getName());
  62. }
  63. }
  64. } catch (IOException e) {
  65. System.err.println("IOException");
  66. }
  67. }
  68. }
  69.  
  70.  
  71.  
  72. package IO;
  73.  
  74. import java.io.*;
  75.  
  76. public class FileExample {
  77. public FileExample() {
  78. super();// 调用父类的构造函数
  79. }
  80.  
  81. public static void main(String[] args) {
  82. try {
  83. String outfile = "demoout.xml";
  84. // 定义了一个变量, 用于标识输出文件
  85. String infile = "demoin.xml";
  86. // 定义了一个变量, 用于标识输入文件
  87. /**
  88. * 用FileOutputStream定义一个输入流文件,
  89. * 然后用BuferedOutputStream调用FileOutputStream对象生成一个缓冲输出流
  90. * 然后用DataOutputStream调用BuferedOutputStream对象生成数据格式化输出流
  91. */
  92. dt, "gbk"));// 对中文的处理
  93. /**
  94. *用FileInputStream定义一个输入流文件,
  95. * 然后用BuferedInputStream调用FileInputStream对象生成一个缓冲输出流
  96. * ,其后用DataInputStream中调用BuferedInputStream对象生成数据格式化输出流
  97. */
  98. rafFile1, "gbk"));// 对中文的处理
  99. String xmlcontent = "";
  100. char tag = 0;// 文件用字符零结束
  101. while (tag != (char) (-1)) {
  102. xmlcontent = xmlcontent + tag + rafFile.readLine() + '
  103. ';
  104. }
  105. NewFile.write(xmlcontent);
  106. NewFile.flush();// 清空缓冲区
  107. NewFile.close();
  108. rafFile.close();
  109. System.gc();// 强制立即回收垃圾,即释放内存。
  110. } catch (NullPointerException exc) {
  111. exc.printStackTrace();
  112. } catch (java.lang.IndexOutOfBoundsException outb) {
  113. System.out.println(outb.getMessage());
  114. outb.printStackTrace();
  115. } catch (FileNotFoundException fex) {
  116. System.out.println("fex" + fex.getMessage());
  117. } catch (IOException iex) {
  118. System.out.println("iex" + iex.getMessage());
  119. }
  120. }
  121. }
  122.  
  123.  
  124. package IO;
  125.  
  126. import java.io.*;
  127.  
  128.  
  129. public class FileRandomRW {
  130. // 需要输入的person数目。
  131. public static int NUMBER = 3;
  132.  
  133. public static void main(String[] args) {
  134. Persons[] people = new Persons[NUMBER];
  135. people[0] = new Persons("张峰", 26, 2000, "N");
  136. people[1] = new Persons("艳娜", 25, 50000, "Y");
  137. people[2] = new Persons("李朋", 50, 7000, "F");
  138. try {
  139. "peoplerandom.dat"));
  140. // 将人员数据保存至“peoplerandom.dat”二进制文件中。
  141. writeData(people, out);
  142. // 关闭流。
  143. out.close();
  144. // 从二进制文件“peoplerandom.dat”中逆序读取数据。
  145. RandomAccessFile inOut = new RandomAccessFile("peoplerandom.dat",
  146. "rw");
  147. Persons[] inPeople = readDataReverse(inOut);
  148. // 输出读入的数据。
  149. System.out.println("原始数据:");
  150. for (int i = 0; i < inPeople.length; i++) {
  151. System.out.println(inPeople[i]);
  152. }
  153. // 修改文件的第三条记录。
  154. inPeople[2].setSalary(4500);
  155. // 将修改结果写入文件。
  156. inPeople[2].writeData(inOut, 3);
  157. // 关闭流。
  158. inOut.close();
  159. // 从文件中读入的第三条记录,并输出,以验证修改结果。
  160. RandomAccessFile in = new RandomAccessFile("peoplerandom.dat", "r");
  161. Persons in3People = new Persons();
  162. // 随机读第三条记录。
  163. in3People.readData(in, 3);
  164. // 关闭流。
  165. in.close();
  166. System.out.println("修改后的记录");
  167. System.out.println(in3People);
  168. } catch (IOException exception) {
  169. System.err.println("IOException");
  170. }
  171. }
  172.  
  173. // 将数据写入输出流。
  174. static void writeData(Persons[] p, DataOutputStream out) throws IOException {
  175. for (int i = 0; i < p.length; i++) {
  176. p[i].writeData(out);
  177. }
  178. }
  179.  
  180. // 将数据从输入流中逆序读出。
  181. static Persons[] readDataReverse(RandomAccessFile in) throws IOException {
  182. // 获得记录数目。
  183. int record_num = (int) (in.length() / Persons.RECORD_LENGTH);
  184. Persons[] p = new Persons[record_num];
  185. // 逆序读取。
  186. for (int i = record_num - 1; i >= 0; i--) {
  187. p[i] = new Persons();
  188. // 文件定位。
  189. in.seek(i * Persons.RECORD_LENGTH);
  190. p[i].readData(in, i + 1);
  191. }
  192. return p;
  193. }
  194. }
  195.  
  196. class Persons {
  197. private String name;
  198. private int age; // 4个字节
  199. private double salary; // 8个字节
  200. private String married;
  201.  
  202. public static final int NAME_LENGTH = 20; // 姓名长度
  203. public static final int MARRIED_LENGTH = 2; // 婚否长度
  204. public static final int RECORD_LENGTH = NAME_LENGTH * 2 + 4 + 8
  205. + MARRIED_LENGTH * 2;
  206.  
  207. public Persons() {
  208. }
  209.  
  210. public Persons(String n, int a, double s) {
  211. name = n;
  212. age = a;
  213. salary = s;
  214. married = "F";
  215. }
  216.  
  217. public Persons(String n, int a, double s, String m) {
  218. name = n;
  219. age = a;
  220. salary = s;
  221. married = m;
  222. }
  223.  
  224. public String getName() {
  225. return name;
  226. }
  227.  
  228. public int getAge() {
  229. return age;
  230. }
  231.  
  232. public double getSalary() {
  233. return salary;
  234. }
  235.  
  236. public String getMarried() {
  237. return married;
  238. }
  239.  
  240. public String setName(String n) {
  241. name = n;
  242. return name;
  243. }
  244.  
  245. public int setAge(int a) {
  246. age = a;
  247. return age;
  248. }
  249.  
  250. public double setSalary(double s) {
  251. salary = s;
  252. return salary;
  253. }
  254.  
  255. public String setMarried(String m) {
  256. married = m;
  257. return married;
  258. }
  259.  
  260. // 设置输出格式。
  261. public String toString() {
  262. return getClass().getName() + "[name=" + name + ",age=" + age
  263. + ",salary=" + salary + ",married=" + married + "]";
  264. }
  265.  
  266. // 写入一条固定长度的记录,即一个人的数据到输出流。
  267. public void writeData(DataOutput out) throws IOException {
  268. FixStringIO.writeFixString(name, NAME_LENGTH, out);
  269. out.writeInt(age);
  270. out.writeDouble(salary);
  271. FixStringIO.writeFixString(married, MARRIED_LENGTH, out);
  272. }
  273.  
  274. // 写入一条固定长度的记录到随机读取文件中。
  275. private void writeData(RandomAccessFile out) throws IOException {
  276. FixStringIO.writeFixString(name, NAME_LENGTH, out);
  277. out.writeInt(age);
  278. out.writeDouble(salary);
  279. FixStringIO.writeFixString(married, MARRIED_LENGTH, out);
  280. }
  281.  
  282. // 随机写入一条固定长度的记录到输出流的指定位置。
  283. public void writeData(RandomAccessFile out, int n) throws IOException {
  284. out.seek((n - 1) * RECORD_LENGTH);
  285. writeData(out);
  286. }
  287.  
  288. // 从输入流随机读入一条记录,即一个人的数据。
  289. private void readData(RandomAccessFile in) throws IOException {
  290. name = FixStringIO.readFixString(NAME_LENGTH, in);
  291. age = in.readInt();
  292. salary = in.readDouble();
  293. married = FixStringIO.readFixString(MARRIED_LENGTH, in);
  294. }
  295.  
  296. // 从输入流随机读入指定位置的记录。
  297. public void readData(RandomAccessFile in, int n) throws IOException {
  298. in.seek((n - 1) * RECORD_LENGTH);
  299. readData(in);
  300. }
  301. }
  302.  
  303. // 对固定长度字符串从文件读出、写入文件
  304. class FixStringIO {
  305. // 读取固定长度的Unicode字符串。
  306. public static String readFixString(int size, DataInput in)
  307. throws IOException {
  308. StringBuffer b = new StringBuffer(size);
  309. int i = 0;
  310. boolean more = true;
  311.  
  312. while (more && i < size) {
  313. char ch = in.readChar();
  314. i++;
  315. if (ch == 0) {
  316. more = false;
  317. } else {
  318. b.append(ch);
  319. }
  320. }
  321. // 跳过剩余的字节。
  322. in.skipBytes(2 * (size - i));
  323. return b.toString();
  324. }
  325.  
  326. // 写入固定长度的Unicode字符串。
  327. public static void writeFixString(String s, int size, DataOutput out)
  328. throws IOException {
  329. int i;
  330. for (i = 0; i < size; i++) {
  331. char ch = 0;
  332. if (i < s.length()) {
  333. ch = s.charAt(i);
  334. }
  335. out.writeChar(ch);
  336. }
  337. }
  338. }
  339.  
  340.  
  341.  
  342. package IO;
  343.  
  344. import java.io.*;
  345. import java.util.*;
  346.  
  347. public class FileRW {
  348. // 需要输入的person数目。
  349. public static int NUMBER = 3;
  350.  
  351. public static void main(String[] args) {
  352. Person[] people = new Person[NUMBER];
  353. // 暂时容纳输入数据的临时字符串数组。
  354. String[] field = new String[4];
  355. // 初始化field数组。
  356. for (int i = 0; i < 4; i++) {
  357. field[i] = "";
  358. }
  359. // IO操作必须捕获IO异常。
  360. try {
  361. // 用于对field数组进行增加控制。
  362. int fieldcount = 0;
  363.  
  364. // 先使用System.in构造InputStreamReader,再构造BufferedReader。
  365. System.in));
  366. for (int i = 0; i < NUMBER; i++) {
  367. fieldcount = 0;
  368. System.out.println("The number " + (i + 1) + " person");
  369. System.out
  370. .println("Enter name,age,salary,married(optional),please separate fields by ':'");
  371. // 读取一行。
  372. String personstr = stdin.readLine();
  373. // 设置分隔符。
  374. StringTokenizer st = new StringTokenizer(personstr, ":");
  375. // 判断是否还有分隔符可用。
  376. while (st.hasMoreTokens()) {
  377. field[fieldcount] = st.nextToken();
  378. fieldcount++;
  379. }
  380. // 如果输入married,则field[3]不为空,调用具有四个参数的Person构造函数。
  381. if (field[3] != "") {
  382. people[i] = new Person(field[0],
  383. Integer.parseInt(field[1]), Double
  384. .parseDouble(field[2]), field[3]);
  385. // 置field[3]为空,以备下次输入使用。
  386. field[3] = "";
  387. }
  388. // 如果未输入married,则field[3]为空,调用具有三个参数的Person构造函数。
  389. else {
  390. people[i] = new Person(field[0],
  391. Integer.parseInt(field[1]), Double
  392. .parseDouble(field[2]));
  393. }
  394. }
  395. // 将输入的数据保存至“people.dat”文本文件中。
  396. new FileWriter("people.dat")));
  397. writeData(people, out);
  398. // 关闭流。
  399. out.close();
  400. // 从文件“people.dat”读取数据。
  401. BufferedReader in = new BufferedReader(new FileReader("people.dat"));
  402. Person[] inPeople = readData(in);
  403. // 关闭流。
  404. in.close();
  405. // 输出从文件中读入的数据。
  406. for (int i = 0; i < inPeople.length; i++) {
  407. System.out.println(inPeople[i]);
  408. }
  409. } catch (IOException exception) {
  410. System.err.println("IOException");
  411. }
  412. }
  413.  
  414. // 将所有数据写入输出流。
  415. static void writeData(Person[] p, PrintWriter out) throws IOException {
  416. // 写入记录条数,即人数。
  417. out.println(p.length);
  418. for (int i = 0; i < p.length; i++) {
  419. p[i].writeData(out);
  420. }
  421. }
  422.  
  423. // 将所有数据从输入流中读出。
  424. static Person[] readData(BufferedReader in) throws IOException {
  425. // 获取记录条数,即人数。
  426. int n = Integer.parseInt(in.readLine());
  427.  
  428. Person[] p = new Person[n];
  429. for (int i = 0; i < n; i++) {
  430. p[i] = new Person();
  431. p[i].readData(in);
  432. }
  433. return p;
  434. }
  435. }
  436.  
  437. class Person {
  438. private String name;
  439. private int age;
  440. private double salary;
  441. private String married;
  442.  
  443. public Person() {
  444. }
  445.  
  446. public Person(String n, int a, double s) {
  447. name = n;
  448. age = a;
  449. salary = s;
  450. married = "F";
  451. }
  452.  
  453. public Person(String n, int a, double s, String m) {
  454. name = n;
  455. age = a;
  456. salary = s;
  457. married = m;
  458. }
  459.  
  460. public String getName() {
  461. return name;
  462. }
  463.  
  464. public int getAge() {
  465. return age;
  466. }
  467.  
  468. public double getSalary() {
  469. return salary;
  470. }
  471.  
  472. public String getMarried() {
  473. return married;
  474. }
  475.  
  476. // 设置输出格式。
  477. public String toString() {
  478. return getClass().getName() + "[name=" + name + ",age=" + age
  479. + ",salary=" + salary + ",married=" + married + "]";
  480. }
  481.  
  482. // 写入一条记录,即一个人的数据到输出流。
  483. public void writeData(PrintWriter out) throws IOException {
  484. // 格式化输出。
  485. out.println(name + ":" + age + ":" + salary + ":" + married);
  486. }
  487.  
  488. // 从输入流读入一条记录,即一个人的数据。
  489. public void readData(BufferedReader in) throws IOException {
  490. String s = in.readLine();
  491. name = t.nextToken();
  492. age = Integer.parseInt(t.nextToken());
  493. salary = Double.parseDouble(t.nextToken());
  494. married = t.nextToken();
  495. }
  496. }
  497.  
  498.  
  499.  
  500. package IO;
  501.  
  502. import java.io.IOException;
  503.  
  504. public class FileStdRead {
  505. public static void main(String[] args) throws IOException {
  506. int b = 0;
  507. char c = ' ';
  508. System.out.println("请输入:");
  509. while (c != 'q') {
  510. int a = System.in.read();
  511. c = (char) a;
  512. b++;
  513. System.out.println((char) a);
  514. }
  515. System.err.print("counted    " + b + "    totalbytes.");
  516. }
  517.  
  518. }
  519. //读取输入的数据,直到数据中有Q这个字母然
  520.  
  521.  
  522. package IO;
  523.  
  524. import java.io.*;
  525.  
  526. public class IOStreamExample {
  527. public static void main(String[] args) throws IOException {
  528. // 1. 读入一行数据:
  529. "FileStdRead.java"));
  530. String s, s2 = new String();
  531. while ((s = in.readLine()) != null) {
  532. s2 += s + "
  533. ";
  534. }
  535. in.close();
  536. System.in));
  537. System.out.print("Enter a line:");
  538. System.out.println(stdin.readLine());
  539. // 2. 从内存中读入
  540. StringReader in2 = new StringReader(s2);
  541. int c;
  542. while ((c = in2.read()) != -1) {
  543. System.out.print((char) c);
  544. }
  545. // 3. 格式化内存输入
  546. try {
  547. s2.getBytes()));
  548. while (true) {
  549. System.out.print((char) in3.readByte());
  550. }
  551. } catch (EOFException e) {
  552. System.err.println("End of stream");
  553. }
  554. // 4. 文件输入
  555. try {
  556. new FileWriter("IODemo.out")));
  557. int lineCount = 1;
  558. while ((s = in4.readLine()) != null) {
  559. out1.println(lineCount++ + ": " + s);
  560. }
  561. out1.close();
  562. } catch (EOFException e) {
  563. System.err.println("End of stream");
  564. }
  565. // 5. 接收和保存数据
  566. try {
  567. new BufferedOutputStream(new FileOutputStream("Data.txt")));
  568. out2.writeDouble(3.14159);
  569. out2.writeUTF("That was pi");
  570. out2.writeDouble(1.41413);
  571. out2.writeUTF("Square root of 2");
  572. out2.close();
  573. new FileInputStream("Data.txt")));
  574.  
  575. System.out.println(in5.readDouble());
  576.  
  577. System.out.println(in5.readUTF());
  578. System.out.println(in5.readDouble());
  579. System.out.println(in5.readUTF());
  580. } catch (EOFException e) {
  581. throw new RuntimeException(e);
  582. }
  583. // 6. 随机读取文件内容
  584. RandomAccessFile rf = new RandomAccessFile("rtest.dat", "rw");
  585. for (int i = 0; i < 10; i++) {
  586. rf.writeDouble(i * 1.414);
  587. }
  588. rf.close();
  589. rf = new RandomAccessFile("rtest.dat", "rw");
  590. rf.seek(5 * 8);
  591. rf.writeDouble(47.0001);
  592. rf.close();
  593. rf = new RandomAccessFile("rtest.dat", "r");
  594. for (int i = 0; i < 10; i++) {
  595. System.out.println("Value " + i + ": " + rf.readDouble());
  596. }
  597. rf.close();
  598. }
  599. }
  600.  
  601.  
  602.  
  603. package IO;
  604.  
  605. import java.io.*;
  606.  
  607. /**
  608. * <p>
  609. * Title: JAVA进阶诀窍
  610. * </p>
  611. *
  612. *  张峰
  613. *  1.0
  614. */
  615. public class MakeDirectoriesExample {
  616. private static void fileattrib(File f) {
  617. System.out.println("绝对路径: " + f.getAbsolutePath() + "
  618. 可读属性: "
  619. + f.canRead() + "
  620. 可定属性: " + f.canWrite() + "
  621. 文件名: "
  622. + f.getName() + "
  623. 父目录: " + f.getParent() + "
  624. 当前路径: "
  625. + f.getPath() + "
  626. 文件长度: " + f.length() + "
  627. 最后更新日期: "
  628. + f.lastModified());
  629. if (f.isFile()) {
  630. System.out.println("输入的是一个文件");
  631. } else if (f.isDirectory()) {
  632. System.out.println("输入的是一个目录");
  633. }
  634. }
  635.  
  636. public static void main(String[] args) {
  637. if (args.length < 1) {
  638. args = new String[3];
  639. }
  640. args[0] = "d";
  641. args[1] = "test1.txt";
  642. args[2] = "test2.txt";
  643. File old = new File(args[1]), rname = new File(args[2]);
  644. old.renameTo(rname);
  645. fileattrib(old);
  646. fileattrib(rname);
  647. int count = 0;
  648. boolean del = false;
  649. if (args[0].equals("d")) {
  650. count++;
  651. del = true;
  652. }
  653. count--;
  654. while (++count < args.length) {
  655. File f = new File(args[count]);
  656. if (f.exists()) {
  657. System.out.println(f + " 文件己经存在");
  658. if (del) {
  659. System.out.println("删除文件" + f);
  660. f.delete();
  661. }
  662. } else { // 如果文件不存在
  663. if (!del) {
  664. f.mkdirs();
  665. System.out.println("创建文件: " + f);
  666. }
  667. }
  668. fileattrib(f);
  669. }
  670. }
  671. }  
  672. //java/1317

回复 "经典代码 java io"

这儿你可以回复上面这条便签

captcha