本文共 3529 字,大约阅读时间需要 11 分钟。
文件操作是Java编程中十分基础但也十分重要的内容。以下是关于文件操作的实践案例:
首先,我们需要创建一个文件:
File file = new File("G://HelloWorld.txt");if (!file.exists()) { try { file.createNewFile(); System.out.println("创建文件成功"); } catch (IOException e) { e.printStackTrace(); }} 接着,我们可以判断文件的类型:
if (file.isDirectory()) { System.out.println("这是个目录");} else { System.out.println("这是一个文件");} 创建文件夹的逻辑与文件创建类似:
File dir = new File("G://IOTest");if (!dir.exists()) { dir.mkdir();} 为了实现文件的复制操作,我们可以使用FileInputStream和FileOutputStream:
FileInputStream in = null;FileOutputStream out = null;try { in = new FileInputStream("G://HelloWorld.txt"); out = new FileOutputStream("G://IOTest//HelloWorld.txt"); int len = 0; while ((len = in.read()) != -1) { out.write(len); } System.out.println("文件移动成功"); // 遍历输出文件 System.out.println("IOTest目录下的文件如下:"); File[] list = dir.listFiles(); for (File file1 : list) { System.out.println(file1.getName()); }} catch (FileNotFoundException e) { e.printStackTrace();} catch (IOException e) { e.printStackTrace();} finally { if (in != null) { try { in.close(); } catch (IOException e) { e.printStackTrace(); } } if (out != null) { try { out.close(); } catch (IOException e) { e.printStackTrace(); } }} 公鸡每只15元,母鸡每只9元,小鸡每只1元。已知:
通过建立方程组解决问题:
通过消元法化简方程,最终得到:
public class Exam2 { public static void main(String[] args) { for (int i = 0; i <= 20; i++) { for (int j = 0; j <= 34; j++) { for (int k = 0; k <= 100; k++) { if (15 * i + 9 * j + k == 300 && i + j + k == 100) { System.out.println("公鸡" + i + ", 母鸡" + j + ", 小鸡" + k); } } } } }} 为了提高效率,可以通过缩小变量范围:
以下是一个使用HashMap的实际案例:
class BankAccount { String id; String name; double money; public BankAccount(String id, String name, double money) { this.id = id; this.name = name; this.money = money; } @Override public String toString() { return "储户id:" + id + "\t" + "姓名" + name + "\t" + "余额" + money; }} public class Exam3 { public static void main(String[] args) { HashMap hashMap = new HashMap<>(); hashMap.put("101", new BankAccount("101", "祝枝山", 10000.0)); hashMap.put("102", new BankAccount("102", "文征明", 20000.0)); hashMap.put("103", new BankAccount("103", "唐伯虎", 30000.0)); if (hashMap.containsKey("102")) { System.out.println("检索id为102的储户信息如下:\n" + hashMap.get("102")); } System.out.println("遍历哈希表结果如下:"); Iterator iterator = hashMap.keySet().iterator(); while (iterator.hasNext()) { String key = iterator.next(); BankAccount value = hashMap.get(key); System.out.println(value); } }} 以上内容涵盖了Java编程中的文件操作、算法逻辑和集合应用,适合作为编程练习内容。
转载地址:http://kweq.baihongyu.com/