本文共 3534 字,大约阅读时间需要 11 分钟。
interface UserDao { public abstract boolean isLogin(String username, String password); public abstract void regist(User user);}
class UserDaoImpl implements UserDao { private static File file = new File("user.txt"); static { try { file.createNewFile(); } catch (IOException e) { System.out.println("创建文件失败."); // e.printStackTrace(); } } // 其他实现代码...}
BufferedReader br = new BufferedReader(new FileReader(file));String line = null;while ((line = br.readLine()) != null) { String[] datas = line.split("="); if (datas[0].equals(username) && datas[1].equals(password)) { flag = true; break; }}
try { // 读取逻辑} catch (FileNotFoundException e) { System.out.println("用户登录找不到信息所在的文件.");} catch (IOException e) { System.out.println("用户登录失败.");} finally { // 资源释放逻辑}
BufferedWriter bw = new BufferedWriter(new FileWriter(file, true));bw.write(user.getUsername() + "=" + user.getPassword());bw.newLine();bw.flush();
try { // 写入逻辑} catch (IOException e) { System.out.println("用户注册失败.");} finally { // 资源释放逻辑}
DataOutputStream dos = new DataOutputStream(new FileOutputStream("dos.txt"));dos.writeByte(10);dos.writeShort(100);dos.writeInt(1000);
DataInputStream dis = new DataInputStream(new FileInputStream("dos.txt"));byte b = dis.readByte();short s = dis.readShort();
ByteArrayOutputStream baos = new ByteArrayOutputStream();baos.write("hello".getBytes());byte[] bys = baos.toByteArray();ByteArrayInputStream bais = new ByteArrayInputStream(bys);
CharArrayReader car = new CharArrayReader("abc".toCharArray());char c = car.read();
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out));bw.write("hello");bw.newLine();
RandomAccessFile raf = new RandomAccessFile("raf.txt", "rw");raf.writeInt(100);raf.writeChar('a');
raf.seek(4);String str = raf.readUTF();
SequenceInputStream sis = new SequenceInputStream(new FileInputStream("a.txt"), new FileInputStream("b.txt"));BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream("c.txt"));byte[] buffer = new byte[1024];while ((len = sis.read(buffer)) != -1) { bos.write(buffer, 0, len);}
ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("oos.txt"));oos.writeObject(new Person("Tom", 3));
ObjectInputStream ois = new ObjectInputStream(new FileInputStream("oos.txt"));Person p = ois.readObject();
Properties prop = new Properties();prop.setProperty("Jack", "5");prop.setProperty("Tom", "2");
prop.store(new FileWriter("Store.txt"), "Tips:");Properties loadedProp = new Properties();loadedProp.load(new FileReader("Store.txt"));
Path path = Paths.get("file.txt");Files.copy(path, new FileOutputStream("copy.txt"));
Files.write(Paths.get("Array.txt"), "hello world", Charset.forName("GBK"));
通过以上内容,可以清晰地了解Java IO流的操作流程和相关技术。每个部分都包含了具体的代码示例和详细解释,帮助开发者更好地理解和应用这些功能。
转载地址:http://xewiz.baihongyu.com/