當前位置:首頁 » 編程軟體 » 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);

}
}

你的分少的可憐 我給你的功能自然不全

熱點內容
centos使用python 發布:2024-05-18 23:39:48 瀏覽:867
幻影天龍腳本 發布:2024-05-18 23:38:17 瀏覽:712
編程的py 發布:2024-05-18 23:36:22 瀏覽:74
安卓系統怎麼改序列號 發布:2024-05-18 23:28:16 瀏覽:783
c語言中實數 發布:2024-05-18 23:21:03 瀏覽:895
伺服器搭建題目 發布:2024-05-18 23:01:29 瀏覽:28
下載武裝突襲後怎麼進伺服器 發布:2024-05-18 22:56:17 瀏覽:825
c語言字元串大寫變小寫 發布:2024-05-18 22:56:16 瀏覽:438
重啟刪除的文件夾 發布:2024-05-18 22:34:11 瀏覽:638
視頻軟體源碼 發布:2024-05-18 22:22:24 瀏覽:429