String test=args[0];提示数据越界为什么,好菜哦,都是细节

本文探讨了Java中数据越界异常的问题,通过一个简单的代码示例解释了当尝试访问数组中不存在的元素时,程序将抛出ArrayIndexOutOfBoundsException异常的原因。

String test=args[0];提示数据越界为什么

public class ExTestDrive {
public static void main(String[] args){
String test=args[0];

 

 

package com.itgaohe.iodemo.iopractice; import java.io.*; import java.util.Scanner; public class AutoLoad { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); // 自动登录 String parentDirctory = "src\\userinfo"; String childPath = "cookie.txt"; String sourcePath = "src\\userinfo\\test.txt"; String src = "src\\userinfo\\cookie.txt"; // 自动登录 if (autoLoad(src, sourcePath)) { System.out.println("自动登录成功"); } else { System.out.println("用户名或密码错误,登录失败"); // 手动登录 load(scanner,sourcePath,src); } } // 创建文件cookie文件方法 public static void create(String parentDirctory, String childPath) { File parent = new File(parentDirctory); parent.mkdirs(); File cookie = new File(parent, childPath); try { cookie.createNewFile(); } catch (IOException e) { e.printStackTrace(); } if (cookie.exists()) { System.out.println("创建成功"); } else { System.out.println("创建失败"); } } //读取cookie文件件内容 public static String[] readXXX(String src) { BufferedReader br = null; try { br = new BufferedReader(new FileReader(src)); String saveName = br.readLine(); String savePassword = br.readLine(); return new String[]{saveName, savePassword}; } catch (IOException e) { e.printStackTrace(); } finally { if (br != null) { try { br.close(); } catch (IOException e) { e.printStackTrace(); } } } return null; } // 从userInfo\\test读取信息 public static String[] readTest(String sourcePath) { BufferedReader br = null; try { br = new BufferedReader(new FileReader(sourcePath)); String s = br.readLine(); String[] temp = s.split("&"); String name = temp[0].split("=")[1]; String password = temp[1].split("=")[1]; return new String[]{name, password}; } catch (IOException e) { e.printStackTrace(); } finally { if (br != null) { try { br.close(); } catch (IOException e) { e.printStackTrace(); } } } return null; } // 手动登录验证 public static void load(Scanner scanner, String sourcePath,String src) { String readdata[] = readTest(sourcePath); String inputName= null; String inputPassword = null; if (readdata != null) { String trueName = readdata[0]; String truePassword = readdata[1]; System.out.println("欢迎登录系统"); System.out.println("请输入用户名"); inputName = scanner.nextLine().trim(); System.out.println("请输入密码"); inputPassword = scanner.nextLine().trim(); if (trueName.equals(inputName) && truePassword.equals(inputPassword)) { System.out.println("登录成功信息已保存,下次可自动登录"); } } else { System.out.println("登录失败,用户名或密码错误"); // 保存信息到cookie文件中 writeDate(src,inputName,inputPassword); } } //自动登录验证方法 public static boolean autoLoad(String src, String sourcePath) { // 读取cookie文件的信息 String[] readDate = readXXX(src); String saveName = null; String savePassword = null; if (readDate != null) { saveName = readDate[0]; savePassword = readDate[1]; System.out.println("自动登录中"); } //读取test文件信息 String[] test = readTest(sourcePath); String correctName = null; String correctPassword = null; if (test != null) { correctName = test[0]; correctPassword = test[1]; } // 验证信息是否一致 if (saveName.equals(correctName) && savePassword.equals(correctPassword)) { return true; } else { return false; } } // 将信息写入到cookie文件 public static void writeDate(String src,String username,String password){ BufferedWriter bw = null; try { bw = new BufferedWriter(new FileWriter(src)); bw.write("username="+username); bw.newLine(); bw.write("password="+password); } catch (IOException e) { e.printStackTrace(); }finally { if (bw != null) { try { bw.close(); } catch (IOException e) { e.printStackTrace(); } } } } } 帮我检查修改一下代码
最新发布
10-22
你的代码整体逻辑是清晰的:实现一个简单的“自动登录”功能,通过读取保存在 `cookie.txt` 中的用户名和密码,与原始用户信息文件(`test.txt`)中的内容进行比对。如果匹配,则自动登录成功;否则进入手动登录流程,并将新的登录信息写入 cookie 文件。 不过代码中存在一些 **潜在问题、可优化点以及错误处理不完善的地方**。下面我将逐项分析并提供修改后的完整版本。 --- ### ✅ 存在的问题 1. **`autoLoad()` 方法中未判断 `readDate` 或 `test` 为 null 的情况** 如果 `readXXX(src)` 或 `readTest(sourcePath)` 返回 `null`,后续访问 `readDate[0]` 等会抛出 `NullPointerException`。 2. **`load()` 方法中失败后仍调用 `writeDate()` 写入空值(`inputName`, `inputPassword` 可能为空或无效)** 即使登录失败,也会把用户输入的错误信息写入 cookie 文件,这会导致下次自动登录使用错误凭据。 3. **`writeDate()` 方法没有换行符或格式规范,且未刷新流** 虽然用了 `newLine()`,但最好加上 `bw.flush()` 并确保资源正确释放。 4. **路径分隔符硬编码为反斜杠 `\`,跨平台兼容性差** 应使用 `File.separator` 或直接使用 `/`(Java 支持统一路径写法)。 5. **缺少 `create()` 方法的调用** 在程序开始时并未调用 `create(parentDirctory, childPath)`,可能导致目录或文件不存在而读取失败。 6. **`readTest()` 假设只有一行数据,且结构固定** 需要做基本校验防止数组越界。 7. **`Scanner` 没有关闭** 8. **方法命名不规范**:如 `readXXX` → 更好叫 `readCookie` --- ## ✅ 修改后的完整代码(修复 + 优化) ```java package com.itgaohe.iodemo.iopractice; import java.io.*; import java.util.Scanner; public class AutoLoad { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); String parentDirectory = "src" + File.separator + "userinfo"; String childPath = "cookie.txt"; String sourcePath = parentDirectory + File.separator + "test.txt"; String src = parentDirectory + File.separator + "cookie.txt"; // 确保目录和 cookie 文件存在 create(parentDirectory, childPath); try { if (autoLoad(src, sourcePath)) { System.out.println("自动登录成功"); } else { System.out.println("用户名或密码错误,登录失败"); load(scanner, sourcePath, src); } } finally { scanner.close(); } } // 创建父目录和 cookie 文件 public static void create(String parentDirectory, String childPath) { File parent = new File(parentDirectory); if (!parent.exists()) { boolean dirsCreated = parent.mkdirs(); if (!dirsCreated) { System.err.println("无法创建目录: " + parentDirectory); return; } } File cookie = new File(parent, childPath); if (!cookie.exists()) { try { boolean created = cookie.createNewFile(); if (created) { System.out.println("Cookie 文件创建成功: " + cookie.getAbsolutePath()); } else { System.err.println("Cookie 文件创建失败"); } } catch (IOException e) { e.printStackTrace(); } } } // 读取 cookie.txt 中保存的用户名和密码 public static String[] readCookie(String src) { BufferedReader br = null; try { br = new BufferedReader(new FileReader(src)); String usernameLine = br.readLine(); String passwordLine = br.readLine(); if (usernameLine == null || passwordLine == null) { return null; } // 解析 key=value 格式(更健壮) String savedName = parseValue(usernameLine); String savedPassword = parseValue(passwordLine); if (savedName == null || savedPassword == null) { return null; } return new String[]{savedName, savedPassword}; } catch (IOException e) { System.err.println("读取 Cookie 文件出错: " + src); e.printStackTrace(); return null; } finally { closeQuietly(br); } } // 解析形如 "username=abc" 的键值对 private static String parseValue(String line) { if (line == null || !line.contains("=")) return null; return line.split("=", 2)[1].trim(); } // 从 test.txt 读取正确的用户名和密码 public static String[] readTest(String sourcePath) { BufferedReader br = null; try { br = new BufferedReader(new FileReader(sourcePath)); String line = br.readLine(); if (line == null) return null; String[] parts = line.split("&"); if (parts.length < 2) return null; String namePart = parts[0]; String passPart = parts[1]; if (!namePart.startsWith("username=") || !passPart.startsWith("password=")) { return null; } String name = namePart.substring(9); // "username=".length() == 9 String password = passPart.substring(9); // "password=".length() == 9 return new String[]{name, password}; } catch (IOException e) { System.err.println("读取用户信息文件失败: " + sourcePath); e.printStackTrace(); return null; } finally { closeQuietly(br); } } // 手动登录流程 public static void load(Scanner scanner, String sourcePath, String src) { String[] correctData = readTest(sourcePath); if (correctData == null) { System.out.println("系统用户数据文件损坏或不存在!"); return; } String correctName = correctData[0]; String correctPassword = correctData[1]; System.out.println("欢迎登录系统"); System.out.print("请输入用户名: "); String inputName = scanner.nextLine().trim(); System.out.print("请输入密码: "); String inputPassword = scanner.nextLine().trim(); if (correctName.equals(inputName) && correctPassword.equals(inputPassword)) { System.out.println("登录成功!信息已保存,下次可自动登录。"); writeDate(src, inputName, inputPassword); // 保存到 cookie } else { System.out.println("登录失败,用户名或密码错误。"); // 不保存错误信息到 cookie } } // 自动登录验证 public static boolean autoLoad(String src, String sourcePath) { String[] saved = readCookie(src); String[] correct = readTest(sourcePath); if (saved == null || correct == null) { System.out.println("缺少必要信息,无法自动登录。"); return false; } String savedName = saved[0]; String savedPassword = saved[1]; String correctName = correct[0]; String correctPassword = correct[1]; System.out.println("正在尝试自动登录..."); return correctName.equals(savedName) && correctPassword.equals(savedPassword); } // 将用户名和密码写入 cookie 文件 public static void writeDate(String src, String username, String password) { BufferedWriter bw = null; try { bw = new BufferedWriter(new FileWriter(src)); bw.write("username=" + username); bw.newLine(); bw.write("password=" + password); bw.newLine(); bw.flush(); // 刷新缓冲区 System.out.println("登录信息已保存至: " + src); } catch (IOException e) { System.err.println("写入 Cookie 文件失败: " + src); e.printStackTrace(); } finally { closeQuietly(bw); } } // 安全关闭 Closeable 资源 private static void closeQuietly(Closeable closeable) { if (closeable != null) { try { closeable.close(); } catch (IOException e) { e.printStackTrace(); } } } } ``` --- ## ✅ 主要改进说明: | 改进点 | 说明 | |-------|------| | ✅ `create()` 被显式调用 | 确保目录和文件存在 | | ✅ 使用 `File.separator` | 提高跨平台兼容性 | | ✅ 加强 `null` 和异常判断 | 防止 NPE | | ✅ `readCookie` 和 `readTest` 增加格式解析健壮性 | 支持 `key=value` 解析 | | ✅ `writeDate()` 添加 `flush()` 并封装关闭工具方法 | 避免数据未写入 | | ✅ 登录失败时不保存错误信息 | 防止污染 cookie | | ✅ `Scanner` 正确关闭 | 防止资源泄漏 | --- ## ✅ 示例文件内容要求 ### `src/userinfo/test.txt` ``` username=admin&password=123456 ``` ### `src/userinfo/cookie.txt`(自动生成) ``` username=admin password=123456 ``` --- ## ✅ 运行流程示意 1. 启动程序 → 创建 `userinfo` 目录和 `cookie.txt` 2. 尝试自动登录: - 若 `cookie.txt` 存在且内容与 `test.txt` 匹配 → 自动登录成功 - 否则 → 进入手动登录 3. 手动登录成功后 → 保存新凭据到 `cookie.txt` ---
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值