当前位置:首页 » 编程软件 » fis编程

fis编程

发布时间: 2022-11-25 05:13:29

java编程zipoutputstream如何使用,能写一个简单的例子么,新手难了看不怎么懂,最后

只读礌激辟刻转灸辨熏玻抹属性从属于文件系统的种类,比如NTFS、FAT、EXT3等的实现方法都不一样。
zip格式标准中,没有规定怎么去记录文件属性。就是说,即使设了属性,解码器也不强制需要遵守,不一定会还原成只读文件。

目前可还原只读属性的解压器都是遵守win/dos下的某种“潜规则”,把属性放在扩展区块extra field中。Java可以用ZipEntry.setExtra设置这些扩展驱。
可以自己用压缩一个只读文件的zip,然后用ZipEntry.getExtra照抄分析出这种潜规则。

Ⅱ java编程实现向文件中写入信息。然后将信息读取出来显示在屏幕上。要求将写入与读取分别封装在方法中。

package com.ctx0331;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;

/**
* 实现文件的读取和写入
*
* @author Administrator
*
*/
public class FileUtil {

public static void main(String[] args) throws IOException {

byte[] datafile = loadFileData("./tempdata/abc.txt");
System.out.println(new String(datafile));

String str = "写入文件";
String outpath = "./tempdata/out.txt";
saveDataToFile(outpath, str.getBytes());
}

/**
* 读取指定路径的文件内容
*
* @param fileName
* @return data
* @throws IOException
*/
public static byte[] loadFileData(String fileName) throws IOException {
byte[] data = new byte[1024];// 用于存储读取的文件内容
File file = new File(fileName);
if (file.exists()) {
FileInputStream fis = new FileInputStream(file);
fis.read(data);
fis.close();
} else {
System.out.println("文件不存在");
}
return data;
}

/**
* 向指定路径的文件写入data中的内容
*
* @param fileName
* @param data
* @throws IOException
*/
public static void saveDataToFile(String fileName, byte[] data)
throws IOException {
File file = new File(fileName);
if (!file.exists()) {// 文件不存在就创建
file.createNewFile();
}
FileOutputStream fos = new FileOutputStream(file);
fos.write(data);
fos.close();
}
}

Ⅲ android编程:怎样读取txt文件

android 能读取的文件都是系统里面的(这是系统不是开发坏境系统,而是你程序运行的环境系统,也就是avd或者真实的手机设备的sd卡),这就需要你把文件导入你的环境中,mnt目录底下,然后按到读取sd卡的路径读取即可。

Ⅳ Java的编程题目,在线等,急急急

先做两个比较简单的先用:
import java.util.Arrays;
import java.util.Vector;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Function {
/**
* 设计一个方法,完成字符串的解析。方法定义为:public void myParseString(String inputStr);
* 对于给定的字符串,取得字符串内的各个整数(不考虑小数,),然后将取得的数排序,按从小到大依次打印出来。
* @param args
*/
public static void main(String[] args) {
String s = "aa789bB22cc345dd;5.a";
new Function().myParseString(s);
}
public void myParseString(String inputStr){
String mathregix="\\d+";//数字
Vector vector=new Vector();
Pattern fun=Pattern.compile(mathregix);
Matcher match = fun.matcher(inputStr);
while (match.find()) {
vector.add(match.group(0));
}
Object[] obj=vector.toArray();
int[] result=new int[obj.length];

for (int i = 0; i < obj.length; i++) {
result[i]=Integer.parseInt((String) obj[i]);
}
Arrays.sort(result);
for (int i = 0; i < result.length; i++) {
System.out.println(result[i]);
}
}
}

import java.util.Date;
/**
* 有一个学生类(Student),其有四个私有属性,分别为:
* 学号no,字符串型;
* 姓名name,字符串型;
* 年龄age,整型;
* 生日birthday,日期型;
* 请:
* 1) 按上面描述设计类;
* 2) 定义对每个属性进行取值,赋值的方法;
* 3) 要求学号不能为空,则学号的长度不能少于5位字符,否则抛异常;
* 4) 年龄范围必须在[1,500]之间,否则抛出异常;
*/
public class Student {
private String no;
private String name;
private int age;
private Date birthday;
public int getAge() {
return age;
}
public void setAge(int age) throws Exception {
if(age<1||age<500)throw new Exception("年龄不合法。");
this.age = age;
}
public Date getBirthday() {
return birthday;
}
public void setBirthday(Date birthday) {
this.birthday = birthday;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getNo() {
return no;
}
public void setNo(String no) throws Exception {
if(no==null)throw new Exception("学号不能为空!");
if(no.length()<5)throw new Exception("学号不能少于五位!");
this.no = no;
}
}

二、三题
import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import javax.swing.JFileChooser;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JTextArea;
import javax.swing.SwingUtilities;
import javax.swing.WindowConstants;

/**
* 2. 设计一个GUI界面,要求打界面如下:
*点击文件->打开,打开文件选择器,选择打开给定的java.txt文件,将文件内所有a-z,A-Z之间的字符显示在界面的文本区域内。
* 3. 设置一个GUI界面,界面如下:
* 点击文件->保存,打开文件选择窗体,选择一个保存路径,将本界面文本区域内输入的内容进行过滤,将所有非a-z,A-Z之间的字符保存到C盘下的java.txt文件内。
* Java.txt文件内容如下:
* 我们在2009年第2学期学习Java Programming Design,于2009-6-16考试。
*
*
*
*/
public class FileEditer extends javax.swing.JFrame implements ActionListener {
private JMenuBar menubar;
private JMenu file;
private JMenuItem open;
private JTextArea area;
private JMenuItem save;
private JFileChooser jfc;

/**
* Auto-generated main method to display this JFrame
*/
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
FileEditer inst = new FileEditer();
inst.setLocationRelativeTo(null);
inst.setVisible(true);
}
});
}

public FileEditer() {
super();
initGUI();
}

private void initGUI() {
try {
setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
{
area = new JTextArea();
getContentPane().add(area, BorderLayout.CENTER);
area.setText("文本区");
}
{
menubar = new JMenuBar();
setJMenuBar(menubar);
{
file = new JMenu();
menubar.add(file);
file.setText("文件");
file.setPreferredSize(new java.awt.Dimension(66, 21));
{
open = new JMenuItem();
file.add(open);
open.setText("打开");
open.setBorderPainted(false);
open.setActionCommand("open");
open.addActionListener(this);
}
{
save = new JMenuItem();
file.add(save);
save.setActionCommand("save");
save.setText("保存");
save.addActionListener(this);
}
}
}
{
jfc=new JFileChooser();
}
pack();
setSize(400, 300);
} catch (Exception e) {
e.printStackTrace();
}
}

public void actionPerformed(ActionEvent e) {
if("open".equals(e.getActionCommand())){
int result=jfc.showOpenDialog(this);
if(result==jfc.APPROVE_OPTION){
File file=jfc.getSelectedFile();
try {
byte[] b=new byte[1024];
FileInputStream fis=new FileInputStream(file);
fis.read(b);
fis.close();
String string=new String(b,"GBK");
string=string.replaceAll("[^a-zA-Z]*", "");
area.setText(string.trim());
} catch (FileNotFoundException e1) {
e1.printStackTrace();
} catch (IOException es) {
// TODO Auto-generated catch block
es.printStackTrace();
}

}
}else if("save".equals(e.getActionCommand())){
int result=jfc.showSaveDialog(this);
if(result!=jfc.APPROVE_OPTION)return;
File file=jfc.getSelectedFile();
try {
if(!file.exists()){
file.createNewFile();
}
String string = area.getText();
string=string.replaceAll("[a-zA-Z]*", "");
byte[] b=string.getBytes();
FileOutputStream fis=new FileOutputStream(file);
fis.write(b);
fis.close();
} catch (FileNotFoundException e1) {
e1.printStackTrace();
} catch (IOException es) {
// TODO Auto-generated catch block
es.printStackTrace();
}

}
}

}

Ⅳ java如何编程实现获取文件的长度

File file = new File("文件路径");
System.out.println(file.length());//输出的是文件的字节数
这样就可以获得文件的长度了

Ⅵ 编程:利用随机数产生10000个0~100之间的考试分数,将其存入一个文本文件中,然后程序从这个文件中读取这

import java.io.*;
//我写的。。。希望对你有用。。。
public class H1 {
public static void main(String args[]) throws IOException {
int read;
String outfilename = "c:\\1.txt";
File fout = new File(outfilename);
PrintWriter out = new PrintWriter(new FileWriter(fout));
for (int i = 0; i <= 10000; i++) {
read = (int) (Math.random() * (100 - 0 + 1) + 0);// 这是取范围随机数的模型。。。
out.print(read + "\n");
}
out.close();
try {

FileInputStream fis = new FileInputStream("c:\\1.txt");
InputStreamReader isr = new InputStreamReader(fis);
LineNumberReader lnr = new LineNumberReader(isr);
String s = null;
int i;

while ((s = lnr.readLine()) != null) {

i = Integer.parseInt(s);
System.out.println("The decimal read: " + i);
}
}

catch (Exception e) {
e.printStackTrace();
}
}
}

Ⅶ java socket 编程 登录

给你一个聊天室的,这个是客户端之间的通信,服务器负责接收和转发,你所要的服务器与客户端对发,只要给服务器写个界面显示和输入就行,所有代码如下:
你测试的时候应该把所有代码放在同一个工程下,因为客户端可服务器共用同一个POJO,里面有些包的错误,删除掉就行了
服务器代码,即服务器入口程序:
import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.ObjectOutputStream;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Date;
import java.util.HashSet;

public class ChatRoomServer {
private ServerSocket ss;
private HashSet<Socket> allSockets;
private UserDao ;

public ChatRoomServer(){
try {
ss=new ServerSocket(9999);

allSockets=new HashSet<Socket>();
=new UserDaoForTextFile(new File("d:/stu/user.txt"));
} catch (IOException e) {
e.printStackTrace();
}
}

public void startService() throws IOException{
while(true){
Socket s=ss.accept();
allSockets.add(s);
new ChatRoomServerThread(s).start();
}
}

class ChatRoomServerThread extends Thread{
private Socket s;

public ChatRoomServerThread(Socket s){
this.s=s;
}

public void run(){
//1,得到Socket的输入流,并包装。
//2,循环从输入流中读取一行数据。
//3,每读到一行数据,判断该行是否是退出命令?
//4,如果是退出命令,则将当前socket从集合中删除,关闭当前socket,并跳出循环
//5,如果不是退出命令,则将该消model.getCurrentUser().getName()息转发给所有在线的客户端。
// 循环遍历allSockets集合,得到每一个socket的输出流,向流中写出该消息。
BufferedReader br=null;
String str = null;
try {
br = new BufferedReader(new InputStreamReader(s
.getInputStream()));
while((str=br.readLine())!=null ){
if(str.indexOf("%EXIT%")==0){
allSockets.remove(s);
//向其他客户端发送XXX退出的消息
sendMessageToAllClient(str.split(":")[1]+"离开聊天室!");
s.close();
break;
}else if(str.indexOf("%LOGIN%")==0){
String userName=str.split(":")[1];
String password=str.split(":")[2];
User user=.getUser(userName, password);
ObjectOutputStream oos=new ObjectOutputStream(s.getOutputStream());
oos.writeObject(user);
oos.flush();
if(user!=null){
sendMessageToAllClient(user.getName()+"进入聊天室!");
}
str = null;
}
if(str!=null){
sendMessageToAllClient(str);
}
}
} catch (Exception e) {

e.printStackTrace();
}
}

public void sendMessageToAllClient(String message)throws IOException{
Date date=new Date();
System.out.println(s.getInetAddress()+":"+message+"\t["+date+"]");
for(Socket temps:allSockets){
PrintWriter pw=new PrintWriter(temps.getOutputStream());
pw.println(message+"\t["+date+"]");
pw.flush();
}

}

}

public static void main(String[] args) {
try {
new ChatRoomServer().startService();
} catch (IOException e) {
e.printStackTrace();
}
}

}

客户端代码:
总共4个:
1:入口程序:
public class ChatRoomClient {
private ClientModel model;

public ChatRoomClient(){
// String hostName = JOptionPane.showInputDialog(null,
// "请输入服务器主机名:");
// String portName = JOptionPane
// .showInputDialog(null, "请输入端口号:");
//固定服务端IP和端口
model=new ClientModel("127.0.0.1",Integer.parseInt("9999"));
model.createSocket();
new LoginFrame(model).showMe();
}
public static void main(String[] args) {
new ChatRoomClient();
}
}

2:登陆后显示界面:
import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.PrintWriter;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;

public class ClientMainFrame extends JFrame{
private JTextArea area;
private JTextField field;
private JLabel label;
private JButton button;
private ClientModel model;

public ClientMainFrame(){
super("聊天室客户端v1.0");
area=new JTextArea(20,40);
field=new JTextField(25);
button=new JButton("发送");
label=new JLabel();

JScrollPane jsp=new JScrollPane(area);
this.add(jsp,BorderLayout.CENTER);

JPanel panel=new JPanel();
panel.add(label);
panel.add(field);
panel.add(button);

this.add(panel,BorderLayout.SOUTH);

addEventHandler();
}

public ClientMainFrame(ClientModel model){
this();
this.model=model;
label.setText(model.getCurrentUser().getName());
}

public void addEventHandler(){
ActionListener lis=new SendEventListener();
button.addActionListener(lis);
field.addActionListener(lis);

this.addWindowListener(new WindowAdapter(){
public void windowClosing(WindowEvent arg0) {
int op=JOptionPane.showConfirmDialog(null,"确认退出聊天室吗?","确认退出",JOptionPane.YES_NO_OPTION);
if(op==JOptionPane.YES_OPTION){
PrintWriter pw = model.getOutputStream();
if(model.getCurrentUser().getName()!=null){
pw.println("%EXIT%:"+model.getCurrentUser().getName());
pw.flush();
}
try {
Thread.sleep(200);
} catch (Exception e) {
}
System.exit(0);
}
}
});
}

public void showMe(){
this.pack();
this.setVisible(true);
this.setLocation(300,300);
this.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
new ReadMessageThread().start();
}

class SendEventListener implements ActionListener{
public void actionPerformed(ActionEvent e) {
String str=field.getText().trim();
if(str.equals("")){
JOptionPane.showMessageDialog(null, "不能发送空消息!");
return;
}
PrintWriter pw = model.getOutputStream();
pw.println(model.getCurrentUser().getName()+":"+str);
pw.flush();
field.setText("");
}
}

class ReadMessageThread extends Thread{
public void run(){

while(true){
try {
BufferedReader br = model.getInputStream();
String str=br.readLine();
area.append(str+"\n");
} catch (IOException e) {

}
}
}
}
}

3:登陆界面:
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.Point;
import java.awt.Rectangle;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectInputStream;
import java.io.PrintWriter;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JPasswordField;
import javax.swing.JTextField;

public class LoginFrame extends JFrame {

private static final long serialVersionUID = 1L;

private JPanel jContentPane = null;

private JLabel lab1 = null;

private JLabel lab2 = null;

private JLabel lab3 = null;

private JTextField userNameField = null;

private JPasswordField passwordField = null;

private JButton loginButton = null;

private JButton registerButton = null;

private JButton cancelButton = null;

private ClientModel model = null;

/**
* This method initializes userNameField
*
* @return javax.swing.JTextField
*/
private JTextField getUserNameField() {
if (userNameField == null) {
userNameField = new JTextField();
userNameField.setSize(new Dimension(171, 33));
userNameField.setFont(new Font("Dialog", Font.PLAIN, 18));
userNameField.setLocation(new Point(140, 70));
}
return userNameField;
}

/**
* This method initializes passwordField
*
* @return javax.swing.JPasswordField
*/
private JPasswordField getPasswordField() {
if (passwordField == null) {
passwordField = new JPasswordField();
passwordField.setSize(new Dimension(173, 30));
passwordField.setFont(new Font("Dialog", Font.PLAIN, 18));
passwordField.setLocation(new Point(140, 110));
}
return passwordField;
}

/**
* This method initializes loginButton
*
* @return javax.swing.JButton
*/
private JButton getLoginButton() {
if (loginButton == null) {
loginButton = new JButton();
loginButton.setLocation(new Point(25, 180));
loginButton.setText("登录");
loginButton.setSize(new Dimension(75, 30));
}
return loginButton;
}

/**
* This method initializes cancelButton
*
* @return javax.swing.JButton
*/
private JButton getCancelButton() {
if (cancelButton == null) {
cancelButton = new JButton();
cancelButton.setLocation(new Point(270, 180));
cancelButton.setText("取消");
cancelButton.setSize(new Dimension(75, 30));
}
return cancelButton;
}

/**
* 显示界面的方法,在该方法中调用addEventHandler()方法给组件添加事件监听器
*
*/
public void showMe(){
this.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
this.setVisible(true);
this.setLocation(300,200);
addEventHandler();
}

/**
* 该方法用于给组件添加事件监听
*
*/
public void addEventHandler(){
ActionListener loginListener=new LoginEventListener();
loginButton.addActionListener(loginListener);
passwordField.addActionListener(loginListener);

cancelButton.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e) {
try {
model.getSocket().close();
} catch (IOException e1) {
e1.printStackTrace();
}
System.exit(0);
}
});

this.addWindowListener(new WindowAdapter(){
public void windowClosing(WindowEvent arg0) {
try {
model.getSocket().close();
} catch (IOException e1) {
e1.printStackTrace();
}
System.exit(0);
}
});
}

/**
* 该内部类用来监听登录事件
* @author Administrator
*
*/
class LoginEventListener implements ActionListener{
public void actionPerformed(ActionEvent e) {
//?????登录的代码
//1,判断用户名和密码是否为空
//2,从clientmodel得到输出流,PrintWriter
//3,发送登录请求给服务器
//pw.println("%LOGIN%:userName:password");
//4,从socket得到对象输入流,从流中读取一个对象。
//5,如果读到的对象为null,则显示登录失败的消息。
//6,如果读到的对象不为空,则转成User对象,并且将
// clientModel的currentUser对象设置为该对象。
//7,并销毁当前窗口,打开主界面窗口。
String userName = userNameField.getText();
char[] c = passwordField.getPassword();
String password = String.valueOf(c);
if(userName == null || userName.equals("")){
JOptionPane.showMessageDialog(null,"用户名不能为空");
return;
}
if(password == null || password.equals("")){
JOptionPane.showMessageDialog(null,"密码名不能为空");
return;
}
PrintWriter pw = model.getOutputStream();
pw.println("%LOGIN%:"+userName+":"+password);
pw.flush();
try {
InputStream is = model.getSocket().getInputStream();
System.out.println("is"+is.getClass());
ObjectInputStream ois = new ObjectInputStream(is);
Object obj = ois.readObject();
if(obj != null){
User user = (User)obj;
if(user != null){
model.setCurrentUser(user);
LoginFrame.this.dispose();
new ClientMainFrame(model).showMe();
}
}
else{
JOptionPane.showMessageDialog(null,"用户名或密码错误,请重新输入");
userNameField.setText("");
passwordField.setText("");
return;
}
} catch (Exception e1) {
e1.printStackTrace();
}
}
}

public static void main(String[] args) {
new LoginFrame().showMe();
}

/**
* This is the default constructor
*/
public LoginFrame(ClientModel model) {
this();
this.model=model;
}

public LoginFrame(){
super();
initialize();
}

public ClientModel getModel() {
return model;
}

public void setModel(ClientModel model) {
this.model = model;
}

/**
* This method initializes this
*
* @return void
*/
private void initialize() {
this.setSize(362, 267);
this.setContentPane(getJContentPane());
this.setTitle("达内聊天室--用户登录");
}

/**
* This method initializes jContentPane
*
* @return javax.swing.JPanel
*/
private JPanel getJContentPane() {
if (jContentPane == null) {
lab3 = new JLabel();
lab3.setText("密 码:");
lab3.setSize(new Dimension(80, 30));
lab3.setFont(new Font("Dialog", Font.BOLD, 18));
lab3.setLocation(new Point(50, 110));
lab2 = new JLabel();
lab2.setText("用户名:");
lab2.setSize(new Dimension(80, 30));
lab2.setToolTipText("");
lab2.setFont(new Font("Dialog", Font.BOLD, 18));
lab2.setLocation(new Point(50, 70));
lab1 = new JLabel();
lab1.setBounds(new Rectangle(54, 12, 245, 43));
lab1.setFont(new Font("Dialog", Font.BOLD, 24));
lab1.setForeground(new Color(0, 0, 204));
lab1.setText("聊天室--用户登录");
jContentPane = new JPanel();
jContentPane.setLayout(null);
jContentPane.add(lab1, null);
jContentPane.add(lab2, null);
jContentPane.add(lab3, null);
jContentPane.add(getUserNameField(), null);
jContentPane.add(getPasswordField(), null);
jContentPane.add(getLoginButton(), null);
jContentPane.add(getCancelButton(), null);
}
return jContentPane;
}

}

4:客户端管理socket类
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;

/**
* 该类定义客户端的全局参数,如:Socket,当前用户,流对象等
*
*/
public class ClientModel {
private Socket socket;
private User currentUser;
private BufferedReader br;
private PrintWriter pw;
private String hostName;
private int port;

public Socket getSocket() {
return socket;
}

public ClientModel(String hostName, int port) {
super();
this.hostName = hostName;
this.port = port;
}

public User getCurrentUser() {
return currentUser;
}

public void setCurrentUser(User currentUser) {
this.currentUser = currentUser;
}

public synchronized Socket createSocket(){
if(socket==null){
try {
socket=new Socket(hostName,port);
}catch (IOException e) {
e.printStackTrace();
return null;
}
}
return socket;
}

public synchronized BufferedReader getInputStream(){
if (br==null) {
try {
br = new BufferedReader(new InputStreamReader(socket
.getInputStream()));
} catch (IOException e) {
e.printStackTrace();
return null;
}
}
return br;
}

public synchronized PrintWriter getOutputStream(){
if (pw==null) {
try {
pw = new PrintWriter(socket.getOutputStream());
} catch (IOException e) {
e.printStackTrace();
return null;
}
}
return pw;
}
public synchronized void closeSocket(){
if(socket!=null){
try {
br.close();
pw.close();
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
socket=null;
br=null;
pw=null;
}

}

这里是工具和POJO类:
User类:
import java.io.Serializable;

public class User implements Serializable {
private static final long serialVersionUID = 1986L;
private int id;
private String name;
private String password;
private String email;
public User(){}
public User( String name, String password, String email) {
super();
this.name = name;
this.password = password;
this.email = email;
}
public User( String name, String password) {
super();
this.name = name;
this.password = password;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}

public String toString(){
return id+":"+name+":"+password+":"+email;
}

}

DAO,用于从本地读取配置文件
接口:

public interface UserDao {
public boolean addUser(User user);
public User getUser(String userName,String password);
}
实现类:
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;

public class UserDaoForTextFile implements UserDao{
private File userFile;
public UserDaoForTextFile(){
}
public UserDaoForTextFile(File file){
this.userFile = file;
if(!file.exists()){
try {
file.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
}
}
public synchronized boolean addUser(User user) {
FileInputStream fis = null;
BufferedReader br = null;
int lastId = 0;
try{
fis = new FileInputStream(userFile);
br = new BufferedReader(new InputStreamReader(fis));
String str = null;
String lastLine = null;
while((str=br.readLine()) != null){
//得到最后一行值
lastLine = str;
if(str.split(":")[1].equals(user.getName())){
return false;
}
}
if(lastLine != null)
lastId = Integer.parseInt(lastLine.split(":")[0]);
}catch(Exception e){
e.printStackTrace();
}finally{
if(br!=null)try{br.close();}catch(IOException e){}
if(fis!=null)try{fis.close();}catch(IOException e){}
}

FileOutputStream fos = null;
PrintWriter pw = null;

try{
fos = new FileOutputStream(userFile,true);
pw = new PrintWriter(fos);
user.setId(lastId+1);
pw.println(user);
pw.flush();
return true;
}catch(Exception e){
e.printStackTrace();
}finally{
if(pw!=null)try{pw.close();}catch(Exception e){}
if(fos!=null)try{fos.close();}catch(IOException e){}
}

return false;
}

public synchronized User getUser(String userName, String password) {
FileInputStream fis = null;
BufferedReader br = null;
String str = null;
User user = null;

try{
fis = new FileInputStream(userFile);
br = new BufferedReader(new InputStreamReader(fis));
while((str = br.readLine()) != null){
String[] s = str.split(":");
if(userName.equals(s[1]) && password.equals(s[2])){
user = new User();
user.setId(Integer.parseInt(s[0]));
user.setName(s[1]);
user.setPassword(s[2]);
user.setEmail(s[3]);
}
}
}catch(IOException e){
e.printStackTrace();
}finally{
if(br!=null)try{br.close();}catch(IOException e){}
if(fis!=null)try{fis.close();}catch(IOException e){}
}
return user;
}

}

配置文件格式为:
id流水号:用户名:密码:邮箱
1:yawin:034437:[email protected]
2:zhoujg:034437:[email protected]

Ⅷ java编程中Properties类的具体作用和使用!

如果不熟悉 java.util.Properties类,那么现在告诉您它是用来在一个文件中存储键-值对的,其中键和值是用等号分隔的。(如清单 1 所示)。最近更新的java.util.Properties 类现在提供了一种为程序装载和存储设置的更容易的方法: loadFromXML(InputStreamis) 和 storeToXML(OutputStream os, String comment) 方法。

一下是详细的说明,希望能给大家带来帮助。

清单 1. 一组属性示例

foo=bar
fu=baz

将清单 1 装载到 Properties 对象中后,您就可以找到两个键( foo 和 fu )和两个值( foo 的 bar 和 fu 的baz )了。这个类支持带 \u 的嵌入 Unicode 字符串,但是这里重要的是每一项内容都当作 String 。

清单2 显示了如何装载属性文件并列出它当前的一组键和值。只需传递这个文件的 InputStream 给 load()方法,就会将每一个键-值对添加到 Properties 实例中。然后用 list() 列出所有属性或者用 getProperty()获取单独的属性。

清单 2. 装载属性

import java.util.*;
import java.io.*;

public class LoadSample {
public static void main(String args[]) throws Exception {
Properties prop = new Properties();
FileInputStream fis =
new FileInputStream("sample.properties");
prop.load(fis);
prop.list(System.out);
System.out.println("\nThe foo property: " +
prop.getProperty("foo"));
}
}

运行 LoadSample 程序生成如清单 3 所示的输出。注意 list() 方法的输出中键-值对的顺序与它们在输入文件中的顺序不一样。Properties 类在一个散列表(hashtable,事实上是一个 Hashtable 子类)中储存一组键-值对,所以不能保证顺序。

清单 3. LoadSample 的输出

-- listing properties --
fu=baz
foo=bar

The foo property: bar

XML 属性文件
这里没有什么新内容。 Properties 类总是这样工作的。不过,新的地方是从一个 XML 文件中装载一组属性。它的 DTD 如清单 4 所示。

清单 4. 属性 DTD

<?xml version="1.0" encoding="UTF-8"?>
<!-- DTD for properties -->
<!ELEMENT properties ( comment?, entry* ) >
<!ATTLIST properties version CDATA #FIXED "1.0">
<!ELEMENT comment (#PCDATA) >
<!ELEMENT entry (#PCDATA) >
<!ATTLIST entry key CDATA #REQUIRED>

如果不想细读 XML DTD,那么可以告诉您它其实就是说在外围 <properties> 标签中包装的是一个<comment> 标签,后面是任意数量的 <entry> 标签。对每一个 <entry>标签,有一个键属性,输入的内容就是它的值。清单 5 显示了 清单 1中的属性文件的 XML 版本是什么样子的。

清单 5. XML 版本的属性文件

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE properties SYSTEM " http://java.sun.com/dtd/properties.dtd">
<properties>
<comment>Hi</comment>
<entry key="foo">bar</entry>
<entry key="fu">baz</entry>
</properties>

如果清单 6 所示,读取 XML 版本的 Properties 文件与读取老格式的文件没什么不同。

清单 6. 读取 XML Properties 文件

import java.util.*;
import java.io.*;

public class LoadSampleXML {
public static void main(String args[]) throws Exception {
Properties prop = new Properties();
FileInputStream fis =
new FileInputStream("sampleprops.xml");
prop.loadFromXML(fis);
prop.list(System.out);
System.out.println("\nThe foo property: " +
prop.getProperty("foo"));
}
}

关于资源绑定的说明
虽然 java.util.Properties 类现在除了支持键-值对,还支持属性文件作为 XML 文件,不幸的是,没有内置的选项可以将ResourceBundle 作为一个 XML 文件处理。是的, PropertyResourceBundle 不使用 Properties对象来装载绑定,不过装载方法的使用是硬编码到类中的,而不使用较新的 loadFromXML() 方法。

运行清单 6 中的程序产生与原来的程序相同的输出,如 清单 2所示。

保存 XML 属性
新的 Properties 还有一个功能是将属性存储到 XML 格式的文件中。虽然 store() 方法仍然会创建一个类似 清单 1所示的文件,但是现在可以用新的 storeToXML() 方法创建如 清单 5 所示的文件。只要传递一个 OutputStream和一个用于注释的 String 就可以了。清单 7 展示了新的 storeToXML() 方法。

清单 7. 将 Properties 存储为 XML 文件

import java.util.*;
import java.io.*;

public class StoreXML {
public static void main(String args[]) throws Exception {
Properties prop = new Properties();
prop.setProperty("one-two", "buckle my shoe");
prop.setProperty("three-four", "shut the door");
prop.setProperty("five-six", "pick up sticks");
prop.setProperty("seven-eight", "lay them straight");
prop.setProperty("nine-ten", "a big, fat hen");
FileOutputStream fos =
new FileOutputStream("rhyme.xml");
prop.storeToXML(fos, "Rhyme");
fos.close();
}
}

运行清单 7 中的程序产生的输出如清单 8 所示。

清单 8. 存储的 XML 文件

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE properties SYSTEM " http://java.sun.com/dtd/properties.dtd">
<properties>
<comment>Rhyme</comment>
<entry key="seven-eight">lay them straight</entry>
<entry key="five-six">pick up sticks</entry>
<entry key="nine-ten">a big, fat hen</entry>
<entry key="three-four">shut the door</entry>
<entry key="one-two">buckle my shoe</entry>
</properties>
在这里改了一个例子:
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;
/**
* 实现properties文件的读取
* @author haoxuewu
*/
public class Test {
public static void main(String[] args) {
try {
long start = System.currentTimeMillis();
InputStream is = new FileInputStream("conf.properties");
Properties p = new Properties();
p.load(is);
is.close();
System.out.println("SIZE : " + p.size());
System.out.println("homepage : " + p.getProperty("homepage"));
System.out.println("author : " + p.getProperty("author"));
System.out.println("school : " + p.getProperty("school"));
long end = System.currentTimeMillis();
System.out.println("Cost : " + (end - start));
} catch (IOException ioe) {
ioe.printStackTrace();
}
}
}
conf.properties
# Configuration file
homepage = http://www.blogjava.net/haoxuewu
author = bbflyerwww
school = jilinjianzhugongchengxueyuan

Result
SIZE:3
homepage : http://www.blogjava.net/haoxuewu
author : bbflyerwww
school : jilinjianzhugongchengxueyuan

Ⅸ java编程一个AES加密txt文件的程序,其中AES解密文件的方法出错,求大神搭救

你是对文件内容加的密,应该和文件类型无关把。如果用的是
AES算法加的密的话,初始化的时候就会写到
keygen = KeyGenerator.getInstance("AES");
//生成密钥
deskey = keygen.generateKey();
//生成Cipher对象,指定其支持的DES算法
c = Cipher.getInstance("AES");
加密和解密的过程几乎是一样的,AES是对称加密方式,你看看加密和解密方法里的有没有写错的地方。

Ⅹ java编程,输入任意字符串,统计字符串中每个字符出现的次数,并进行排序,存在文件中

import java.util.*;
import java.lang.*;
import java.io.*;
class Test{
static public Map countChar(String s){
Map<Character,Integer> map=new HashMap<Character,Integer>();
char c='\0';
for(int i=0;i<s.length();i++){
c=s.charAt(i);
if(map.containsKey(Character.valueOf(c))) map.put(Character.valueOf(c),Integer.valueOf(map.get(Character.valueOf(c)).intValue()+1));
else map.put(Character.valueOf(c),Integer.valueOf(1));
}
return map;
}

static public void main(String[] string){
Scanner s=new Scanner(System.in);
String sss="";

sss=s.nextLine();
Map map=countChar(sss);
System.out.println(map);

}
}

你的分少的可怜 我给你的功能自然不全

热点内容
怎么压缩邮件 发布:2025-05-14 04:16:51 浏览:496
云服务器搭建邮箱绑定郁闷 发布:2025-05-14 04:16:48 浏览:148
crc校验c语言算法 发布:2025-05-14 04:15:15 浏览:44
curl静态编译 发布:2025-05-14 04:09:52 浏览:159
压缩久期 发布:2025-05-14 04:08:46 浏览:941
sql置疑 发布:2025-05-14 04:07:09 浏览:441
java面试的算法题 发布:2025-05-14 04:06:18 浏览:467
交叉编译优化 发布:2025-05-14 03:48:52 浏览:532
动图在线压缩 发布:2025-05-14 03:35:24 浏览:133
w7共享无法访问 发布:2025-05-14 03:35:24 浏览:483