你好,代碼如下:
我們提供的服務(wù)有:成都網(wǎng)站建設(shè)、成都網(wǎng)站制作、微信公眾號(hào)開(kāi)發(fā)、網(wǎng)站優(yōu)化、網(wǎng)站認(rèn)證、寧陜ssl等。為1000多家企事業(yè)單位解決了網(wǎng)站和推廣的問(wèn)題。提供周到的售前咨詢和貼心的售后服務(wù),是有科學(xué)管理、有技術(shù)的寧陜網(wǎng)站制作公司
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.Reader;
import java.io.Writer;
public class ReaderDemo02{
public static void main(String args[]) throws Exception{ // 異常拋出,不處理
File f1= new File("c:" + File.separator + "a.txt") ; // 聲明File對(duì)象
File f2= new File("c:" + File.separator + "b.txt") ; // 聲明File對(duì)象
Reader input = null ; // 準(zhǔn)備好一個(gè)輸入的對(duì)象
Writer out = null ;
input = new FileReader(f1) ; // 通過(guò)對(duì)象多態(tài)性,進(jìn)行實(shí)例化
out = new FileWriter(f2) ;
char c[] = new char[1024] ; // 所有的內(nèi)容都讀到此數(shù)組之中
int temp = 0 ; // 接收每一個(gè)內(nèi)容
int len = 0 ; // 讀取內(nèi)容
while((temp=input.read())!=-1){
out.write(temp) ;
c[len] = (char)temp ;
len++ ;
}
input.close() ; // 關(guān)閉輸出流
out.close() ;
System.out.println("內(nèi)容為:" + new String(c,0,len)) ; // 把字符數(shù)組變?yōu)樽址敵?/p>
}
};
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.io.*;
import java.security.*;
import javax.crypto.*;
import javax.crypto.spec.*;
/**
文件名:FileEncrypter.java
JDK:1.40以上
說(shuō)明:文件加密
加密方法:三重DES加密
加密過(guò)程:對(duì)選中的文件加密后在同文件夾下生成一個(gè)增加了".tdes"
擴(kuò)展名的加密文件
解密過(guò)程:對(duì)選中的加密文件(必須有".tdes"擴(kuò)展名)進(jìn)行解密
*/
public class FileEncrypter extends JFrame{
public static final int WIDTH = 550;
public static final int HEIGHT = 200;
public static void main(String args[]) {
FileEncrypter fe = new FileEncrypter();
fe.show();
}
FileEncrypter(){
this.setSize(WIDTH,HEIGHT);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setResizable(false);
Toolkit tk = Toolkit.getDefaultToolkit();
Dimension screenSize = tk.getScreenSize();
this.setLocation((screenSize.width - WIDTH)/2,
(screenSize.height - HEIGHT)/2);
this.setTitle("文件加密器(TriDES)");
Container c = this.getContentPane();
c.setLayout( new FlowLayout());
final FilePanel fp = new FilePanel("文件選擇");
c.add(fp);
final KeyPanel pp = new KeyPanel("密碼");
c.add(pp);
JButton jbE = new JButton("加密");
c.add(jbE);
jbE.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent event){
File file = new File(fp.getFileName());
if (file.exists())
encrypt(file.getAbsoluteFile(),pp.getKey());
else
JOptionPane.showMessageDialog(
null,"請(qǐng)選擇文件!","提示",JOptionPane.OK_OPTION);
}
});
JButton jbD = new JButton("解密");
c.add(jbD);
jbD.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent event){
File file = new File(fp.getFileName());
if (file.exists())
decrypt(file.getAbsoluteFile(),pp.getKey());
else
JOptionPane.showMessageDialog(
null,"請(qǐng)選擇文件!","提示",JOptionPane.OK_OPTION);
}
});
}
/**
加密函數(shù)
輸入:
要加密的文件,密碼(由0-F組成,共48個(gè)字符,表示3個(gè)8位的密碼)如:
AD67EA2F3BE6E5ADD368DFE03120B5DF92A8FD8FEC2F0746
其中:
AD67EA2F3BE6E5AD DES密碼一
D368DFE03120B5DF DES密碼二
92A8FD8FEC2F0746 DES密碼三
輸出:
對(duì)輸入的文件加密后,保存到同一文件夾下增加了".tdes"擴(kuò)展名的文件中。
*/
private void encrypt(File fileIn,String sKey){
try{
if(sKey.length() == 48){
byte[] bytK1 = getKeyByStr(sKey.substring(0,16));
byte[] bytK2 = getKeyByStr(sKey.substring(16,32));
byte[] bytK3 = getKeyByStr(sKey.substring(32,48));
FileInputStream fis = new FileInputStream(fileIn);
byte[] bytIn = new byte[(int)fileIn.length()];
for(int i = 0;iFILEIN.LENGTH();I++){
bytIn[i] = (byte)fis.read();
}
//加密
byte[] bytOut = encryptByDES(encryptByDES(
encryptByDES(bytIn,bytK1),bytK2),bytK3);
String fileOut = fileIn.getPath() + ".tdes";
FileOutputStream fos = new FileOutputStream(fileOut);
for(int i = 0;iBYTOUT.LENGTH;I++){
fos.write((int)bytOut[i]);
}
fos.close();
JOptionPane.showMessageDialog(
this,"加密成功!","提示",JOptionPane.OK_OPTION);
}else
JOptionPane.showMessageDialog(
this,"密碼長(zhǎng)度必須等于48!","錯(cuò)誤信息",JOptionPane.ERROR_MESSAGE);
}catch(Exception e){
e.printStackTrace();
}
}
/**
解密函數(shù)
輸入:
要解密的文件,密碼(由0-F組成,共48個(gè)字符,表示3個(gè)8位的密碼)如:
AD67EA2F3BE6E5ADD368DFE03120B5DF92A8FD8FEC2F0746
其中:
AD67EA2F3BE6E5AD DES密碼一
D368DFE03120B5DF DES密碼二
92A8FD8FEC2F0746 DES密碼三
輸出:
對(duì)輸入的文件解密后,保存到用戶指定的文件中。
*/
private void decrypt(File fileIn,String sKey){
try{
if(sKey.length() == 48){
String strPath = fileIn.getPath();
if(strPath.substring(strPath.length()-5).toLowerCase().equals(".tdes"))
strPath = strPath.substring(0,strPath.length()-5);
else{
JOptionPane.showMessageDialog(
this,"不是合法的加密文件!","提示",JOptionPane.OK_OPTION);
return;
}
JFileChooser chooser = new JFileChooser();
chooser.setCurrentDirectory(new File("."));
chooser.setSelectedFile(new File(strPath));
//用戶指定要保存的文件
int ret = chooser.showSaveDialog(this);
if(ret==JFileChooser.APPROVE_OPTION){
byte[] bytK1 = getKeyByStr(sKey.substring(0,16));
byte[] bytK2 = getKeyByStr(sKey.substring(16,32));
byte[] bytK3 = getKeyByStr(sKey.substring(32,48));
FileInputStream fis = new FileInputStream(fileIn);
byte[] bytIn = new byte[(int)fileIn.length()];
for(int i = 0;iFILEIN.LENGTH();I++){
bytIn[i] = (byte)fis.read();
}
//解密
byte[] bytOut = decryptByDES(decryptByDES(
decryptByDES(bytIn,bytK3),bytK2),bytK1);
File fileOut = chooser.getSelectedFile();
fileOut.createNewFile();
FileOutputStream fos = new FileOutputStream(fileOut);
for(int i = 0;iBYTOUT.LENGTH;I++){
fos.write((int)bytOut[i]);
}
fos.close();
JOptionPane.showMessageDialog(
this,"解密成功!","提示",JOptionPane.OK_OPTION);
}
}else
JOptionPane.showMessageDialog(
this,"密碼長(zhǎng)度必須等于48!","錯(cuò)誤信息",JOptionPane.ERROR_MESSAGE);
}catch(Exception e){
JOptionPane.showMessageDialog(
this,"解密失敗,請(qǐng)核對(duì)密碼!","提示",JOptionPane.OK_OPTION);
}
}
/**
用DES方法加密輸入的字節(jié)
bytKey需為8字節(jié)長(zhǎng),是加密的密碼
*/
private byte[] encryptByDES(byte[] bytP,byte[] bytKey) throws Exception{
DESKeySpec desKS = new DESKeySpec(bytKey);
SecretKeyFactory skf = SecretKeyFactory.getInstance("DES");
SecretKey sk = skf.generateSecret(desKS);
Cipher cip = Cipher.getInstance("DES");
cip.init(Cipher.ENCRYPT_MODE,sk);
return cip.doFinal(bytP);
}
/**
用DES方法解密輸入的字節(jié)
bytKey需為8字節(jié)長(zhǎng),是解密的密碼
*/
private byte[] decryptByDES(byte[] bytE,byte[] bytKey) throws Exception{
DESKeySpec desKS = new DESKeySpec(bytKey);
SecretKeyFactory skf = SecretKeyFactory.getInstance("DES");
SecretKey sk = skf.generateSecret(desKS);
Cipher cip = Cipher.getInstance("DES");
cip.init(Cipher.DECRYPT_MODE,sk);
return cip.doFinal(bytE);
}
/**
輸入密碼的字符形式,返回字節(jié)數(shù)組形式。
如輸入字符串:AD67EA2F3BE6E5AD
返回字節(jié)數(shù)組:{173,103,234,47,59,230,229,173}
*/
private byte[] getKeyByStr(String str){
byte[] bRet = new byte[str.length()/2];
for(int i=0;iSTR.LENGTH()
Integer itg =
new Integer(16*getChrInt(str.charAt(2*i)) + getChrInt(str.charAt(2*i+1)));
bRet[i] = itg.byteValue();
}
return bRet;
}
/**
計(jì)算一個(gè)16進(jìn)制字符的10進(jìn)制值
輸入:0-F
*/
private int getChrInt(char chr){
int iRet=0;
if(chr=="0".charAt(0)) iRet = 0;
if(chr=="1".charAt(0)) iRet = 1;
if(chr=="2".charAt(0)) iRet = 2;
if(chr=="3".charAt(0)) iRet = 3;
if(chr=="4".charAt(0)) iRet = 4;
if(chr=="5".charAt(0)) iRet = 5;
if(chr=="6".charAt(0)) iRet = 6;
if(chr=="7".charAt(0)) iRet = 7;
if(chr=="8".charAt(0)) iRet = 8;
if(chr=="9".charAt(0)) iRet = 9;
if(chr=="A".charAt(0)) iRet = 10;
if(chr=="B".charAt(0)) iRet = 11;
if(chr=="C".charAt(0)) iRet = 12;
if(chr=="D".charAt(0)) iRet = 13;
if(chr=="E".charAt(0)) iRet = 14;
if(chr=="F".charAt(0)) iRet = 15;
return iRet;
}
}
/**
文件選擇組件。
*/
class FilePanel extends JPanel{
FilePanel(String str){
JLabel label = new JLabel(str);
JTextField fileText = new JTextField(35);
JButton chooseButton = new JButton("瀏覽...");
this.add(label);
this.add(fileText);
this.add(chooseButton);
clickAction ca = new clickAction(this);
chooseButton.addActionListener(ca);
}
public String getFileName(){
JTextField jtf = (JTextField)this.getComponent(1);
return jtf.getText();
}
private class clickAction implements ActionListener{
clickAction(Component c){
cmpt = c;
}
public void actionPerformed(ActionEvent event){
JFileChooser chooser = new JFileChooser();
chooser.setCurrentDirectory(new File("."));
int ret = chooser.showOpenDialog(cmpt);
if(ret==JFileChooser.APPROVE_OPTION){
JPanel jp = (JPanel)cmpt;
JTextField jtf = (JTextField)jp.getComponent(1);
jtf.setText(chooser.getSelectedFile().getPath());
}
}
private Component cmpt;
}
}
/**
密碼生成組件。
*/
class KeyPanel extends JPanel{
KeyPanel(String str){
JLabel label = new JLabel(str);
JTextField fileText = new JTextField(35);
JButton chooseButton = new JButton("隨機(jī)產(chǎn)生");
this.add(label);
this.add(fileText);
this.add(chooseButton);
clickAction ca = new clickAction(this);
chooseButton.addActionListener(ca);
}
//返回生成的密碼(48個(gè)字符長(zhǎng)度)
public String getKey(){
JTextField jtf = (JTextField)this.getComponent(1);
return jtf.getText();
}
private class clickAction implements ActionListener{
clickAction(Component c){
cmpt = c;
}
public void actionPerformed(ActionEvent event){
try{
KeyGenerator kg = KeyGenerator.getInstance("DES");
kg.init(56);
Key ke = kg.generateKey();
byte[] bytK1 = ke.getEncoded();
ke = kg.generateKey();
byte[] bytK2 = ke.getEncoded();
ke = kg.generateKey();
byte[] bytK3 = ke.getEncoded();
JPanel jp = (JPanel)cmpt;
JTextField jtf = (JTextField)jp.getComponent(1);
jtf.setText(getByteStr(bytK1)+getByteStr(bytK2)+getByteStr(bytK3));
}catch(Exception e){
e.printStackTrace();
}
}
private String getByteStr(byte[] byt){
String strRet = "";
for(int i=0;iBYT.LENGTH;I++){
//System.out.println(byt[i]);
strRet += getHexValue((byt[i]240)/16);
strRet += getHexValue(byt[i]15);
}
return strRet;
}
private String getHexValue(int s){
String sRet=null;
switch (s){
case 0: sRet = "0";break;
case 1: sRet = "1";break;
case 2: sRet = "2";break;
case 3: sRet = "3";break;
case 4: sRet = "4";break;
case 5: sRet = "5";break;
case 6: sRet = "6";break;
case 7: sRet = "7";break;
case 8: sRet = "8";break;
case 9: sRet = "9";break;
case 10: sRet = "A";break;
case 11: sRet = "B";break;
case 12: sRet = "C";break;
case 13: sRet = "D";break;
case 14: sRet = "E";break;
case 15: sRet = "F";
}
return sRet;
}
private Component cmpt;
}
}
用BufferedReader就可以了
public class Test8
{
public static void main(String[] args) throws Exception
{
BufferedReader br = new BufferedReader(new InputStreamReader(
new FileInputStream(new File(
"C:/Users/Lenovo/Desktop/新建文本文檔.txt"))));
String line = br.readLine();
while (null != line)
{
System.out.print(line);
line = br.readLine();
}
br.close();
}
}
package IO;
import java.io.*;
public class FileDirectoryDemo {
public static void main(String[] args) {
// 如果沒(méi)有指定參數(shù),則缺省為當(dāng)前目錄。
if (args.length == 0) {
args = new String[] { "." };
}
try {
// 新建指定目錄的File對(duì)象。
File currentPath = new File(args[0]);
// 在指定目錄新建temp目錄的File對(duì)象。
File tempPath = new File(currentPath, "temp");
// 用“tempPath”對(duì)象在指定目錄下創(chuàng)建temp目錄。
tempPath.mkdir();
// 在temp目錄下創(chuàng)建兩個(gè)文件。
File temp1 = new File(tempPath, "temp1.txt");
temp1.createNewFile();
File temp2 = new File(tempPath, "temp2.txt");
temp2.createNewFile();
// 遞歸顯示指定目錄的內(nèi)容。
System.out.println("顯示指定目錄的內(nèi)容");
listSubDir(currentPath);
// 更改文件名“temp1.txt”為“temp.txt”。
File temp1new = new File(tempPath, "temp.txt");
temp1.renameTo(temp1new);
// 遞歸顯示temp子目錄的內(nèi)容。
System.out.println("更改文件名后,顯示temp子目錄的內(nèi)容");
listSubDir(tempPath);
// 刪除文件“temp2.txt”。
temp2.delete();
// 遞歸顯示temp子目錄的內(nèi)容。
System.out.println("刪除文件后,顯示temp子目錄的內(nèi)容");
listSubDir(tempPath);
} catch (IOException e) {
System.err.println("IOException");
}
}
// 遞歸顯示指定目錄的內(nèi)容。
static void listSubDir(File currentPath) {
// 取得指定目錄的內(nèi)容列表。
String[] fileNames = currentPath.list();
try {
for (int i = 0; i fileNames.length; i++) {
File f = new File(currentPath.getPath(), fileNames[i]);
// 如果是目錄,則顯示目錄名后,遞歸調(diào)用,顯示子目錄的內(nèi)容。
if (f.isDirectory()) {
// 以規(guī)范的路徑格式顯示目錄。
System.out.println(f.getCanonicalPath());
// 遞歸調(diào)用,顯示子目錄。
listSubDir(f);
}
// 如果是文件,則顯示文件名,不包含路徑信息。
else {
System.out.println(f.getName());
}
}
} catch (IOException e) {
System.err.println("IOException");
}
}
}
package IO;
import java.io.*;
public class FileExample {
public FileExample() {
super();// 調(diào)用父類(lèi)的構(gòu)造函數(shù)
}
public static void main(String[] args) {
try {
String outfile = "demoout.xml";
// 定義了一個(gè)變量, 用于標(biāo)識(shí)輸出文件
String infile = "demoin.xml";
// 定義了一個(gè)變量, 用于標(biāo)識(shí)輸入文件
DataOutputStream dt = new DataOutputStream(
new BufferedOutputStream(new FileOutputStream(outfile)));
/**
* 用FileOutputStream定義一個(gè)輸入流文件,
* 然后用BuferedOutputStream調(diào)用FileOutputStream對(duì)象生成一個(gè)緩沖輸出流
* 然后用DataOutputStream調(diào)用BuferedOutputStream對(duì)象生成數(shù)據(jù)格式化輸出流
*/
BufferedWriter NewFile = new BufferedWriter(new OutputStreamWriter(
dt, "gbk"));// 對(duì)中文的處理
DataInputStream rafFile1 = new DataInputStream(
new BufferedInputStream(new FileInputStream(infile)));
/**
*用FileInputStream定義一個(gè)輸入流文件,
* 然后用BuferedInputStream調(diào)用FileInputStream對(duì)象生成一個(gè)緩沖輸出流
* ,其后用DataInputStream中調(diào)用BuferedInputStream對(duì)象生成數(shù)據(jù)格式化輸出流
*/
BufferedReader rafFile = new BufferedReader(new InputStreamReader(
rafFile1, "gbk"));// 對(duì)中文的處理
String xmlcontent = "";
char tag = 0;// 文件用字符零結(jié)束
while (tag != (char) (-1)) {
xmlcontent = xmlcontent + tag + rafFile.readLine() + '\n';
}
NewFile.write(xmlcontent);
NewFile.flush();// 清空緩沖區(qū)
NewFile.close();
rafFile.close();
System.gc();// 強(qiáng)制立即回收垃圾,即釋放內(nèi)存。
} catch (NullPointerException exc) {
exc.printStackTrace();
} catch (java.lang.IndexOutOfBoundsException outb) {
System.out.println(outb.getMessage());
outb.printStackTrace();
} catch (FileNotFoundException fex) {
System.out.println("fex" + fex.getMessage());
} catch (IOException iex) {
System.out.println("iex" + iex.getMessage());
}
}
}
package IO;
import java.io.*;
public class FileRandomRW {
// 需要輸入的person數(shù)目。
public static int NUMBER = 3;
public static void main(String[] args) {
Persons[] people = new Persons[NUMBER];
people[0] = new Persons("張峰", 26, 2000, "N");
people[1] = new Persons("艷娜", 25, 50000, "Y");
people[2] = new Persons("李朋", 50, 7000, "F");
try {
DataOutputStream out = new DataOutputStream(new FileOutputStream(
"peoplerandom.dat"));
// 將人員數(shù)據(jù)保存至“peoplerandom.dat”二進(jìn)制文件中。
writeData(people, out);
// 關(guān)閉流。
out.close();
// 從二進(jìn)制文件“peoplerandom.dat”中逆序讀取數(shù)據(jù)。
RandomAccessFile inOut = new RandomAccessFile("peoplerandom.dat",
"rw");
Persons[] inPeople = readDataReverse(inOut);
// 輸出讀入的數(shù)據(jù)。
System.out.println("原始數(shù)據(jù):");
for (int i = 0; i inPeople.length; i++) {
System.out.println(inPeople[i]);
}
// 修改文件的第三條記錄。
inPeople[2].setSalary(4500);
// 將修改結(jié)果寫(xiě)入文件。
inPeople[2].writeData(inOut, 3);
// 關(guān)閉流。
inOut.close();
// 從文件中讀入的第三條記錄,并輸出,以驗(yàn)證修改結(jié)果。
RandomAccessFile in = new RandomAccessFile("peoplerandom.dat", "r");
Persons in3People = new Persons();
// 隨機(jī)讀第三條記錄。
in3People.readData(in, 3);
// 關(guān)閉流。
in.close();
System.out.println("修改后的記錄");
System.out.println(in3People);
} catch (IOException exception) {
System.err.println("IOException");
}
}
// 將數(shù)據(jù)寫(xiě)入輸出流。
static void writeData(Persons[] p, DataOutputStream out) throws IOException {
for (int i = 0; i p.length; i++) {
p[i].writeData(out);
}
}
// 將數(shù)據(jù)從輸入流中逆序讀出。
static Persons[] readDataReverse(RandomAccessFile in) throws IOException {
// 獲得記錄數(shù)目。
int record_num = (int) (in.length() / Persons.RECORD_LENGTH);
Persons[] p = new Persons[record_num];
// 逆序讀取。
for (int i = record_num - 1; i = 0; i--) {
p[i] = new Persons();
// 文件定位。
in.seek(i * Persons.RECORD_LENGTH);
p[i].readData(in, i + 1);
}
return p;
}
}
class Persons {
private String name;
private int age; // 4個(gè)字節(jié)
private double salary; // 8個(gè)字節(jié)
private String married;
public static final int NAME_LENGTH = 20; // 姓名長(zhǎng)度
public static final int MARRIED_LENGTH = 2; // 婚否長(zhǎng)度
public static final int RECORD_LENGTH = NAME_LENGTH * 2 + 4 + 8
+ MARRIED_LENGTH * 2;
public Persons() {
}
public Persons(String n, int a, double s) {
name = n;
age = a;
salary = s;
married = "F";
}
public Persons(String n, int a, double s, String m) {
name = n;
age = a;
salary = s;
married = m;
}
public String getName() {
return name;
}
public int getAge() {
return age;
}
public double getSalary() {
return salary;
}
public String getMarried() {
return married;
}
public String setName(String n) {
name = n;
return name;
}
public int setAge(int a) {
age = a;
return age;
}
public double setSalary(double s) {
salary = s;
return salary;
}
public String setMarried(String m) {
married = m;
return married;
}
// 設(shè)置輸出格式。
public String toString() {
return getClass().getName() + "[name=" + name + ",age=" + age
+ ",salary=" + salary + ",married=" + married + "]";
}
// 寫(xiě)入一條固定長(zhǎng)度的記錄,即一個(gè)人的數(shù)據(jù)到輸出流。
public void writeData(DataOutput out) throws IOException {
FixStringIO.writeFixString(name, NAME_LENGTH, out);
out.writeInt(age);
out.writeDouble(salary);
FixStringIO.writeFixString(married, MARRIED_LENGTH, out);
}
// 寫(xiě)入一條固定長(zhǎng)度的記錄到隨機(jī)讀取文件中。
private void writeData(RandomAccessFile out) throws IOException {
FixStringIO.writeFixString(name, NAME_LENGTH, out);
out.writeInt(age);
out.writeDouble(salary);
FixStringIO.writeFixString(married, MARRIED_LENGTH, out);
}
// 隨機(jī)寫(xiě)入一條固定長(zhǎng)度的記錄到輸出流的指定位置。
public void writeData(RandomAccessFile out, int n) throws IOException {
out.seek((n - 1) * RECORD_LENGTH);
writeData(out);
}
// 從輸入流隨機(jī)讀入一條記錄,即一個(gè)人的數(shù)據(jù)。
private void readData(RandomAccessFile in) throws IOException {
name = FixStringIO.readFixString(NAME_LENGTH, in);
age = in.readInt();
salary = in.readDouble();
married = FixStringIO.readFixString(MARRIED_LENGTH, in);
}
// 從輸入流隨機(jī)讀入指定位置的記錄。
public void readData(RandomAccessFile in, int n) throws IOException {
in.seek((n - 1) * RECORD_LENGTH);
readData(in);
}
}
// 對(duì)固定長(zhǎng)度字符串從文件讀出、寫(xiě)入文件
class FixStringIO {
// 讀取固定長(zhǎng)度的Unicode字符串。
public static String readFixString(int size, DataInput in)
throws IOException {
StringBuffer b = new StringBuffer(size);
int i = 0;
boolean more = true;
while (more i size) {
char ch = in.readChar();
i++;
if (ch == 0) {
more = false;
} else {
b.append(ch);
}
}
// 跳過(guò)剩余的字節(jié)。
in.skipBytes(2 * (size - i));
return b.toString();
}
// 寫(xiě)入固定長(zhǎng)度的Unicode字符串。
public static void writeFixString(String s, int size, DataOutput out)
throws IOException {
int i;
for (i = 0; i size; i++) {
char ch = 0;
if (i s.length()) {
ch = s.charAt(i);
}
out.writeChar(ch);
}
}
}
package IO;
import java.io.*;
import java.util.*;
public class FileRW {
// 需要輸入的person數(shù)目。
public static int NUMBER = 3;
public static void main(String[] args) {
Person[] people = new Person[NUMBER];
// 暫時(shí)容納輸入數(shù)據(jù)的臨時(shí)字符串?dāng)?shù)組。
String[] field = new String[4];
// 初始化field數(shù)組。
for (int i = 0; i 4; i++) {
field[i] = "";
}
// IO操作必須捕獲IO異常。
try {
// 用于對(duì)field數(shù)組進(jìn)行增加控制。
int fieldcount = 0;
// 先使用System.in構(gòu)造InputStreamReader,再構(gòu)造BufferedReader。
BufferedReader stdin = new BufferedReader(new InputStreamReader(
System.in));
for (int i = 0; i NUMBER; i++) {
fieldcount = 0;
System.out.println("The number " + (i + 1) + " person");
System.out
.println("Enter name,age,salary,married(optional),please separate fields by ':'");
// 讀取一行。
String personstr = stdin.readLine();
// 設(shè)置分隔符。
StringTokenizer st = new StringTokenizer(personstr, ":");
// 判斷是否還有分隔符可用。
while (st.hasMoreTokens()) {
field[fieldcount] = st.nextToken();
fieldcount++;
}
// 如果輸入married,則field[3]不為空,調(diào)用具有四個(gè)參數(shù)的Person構(gòu)造函數(shù)。
if (field[3] != "") {
people[i] = new Person(field[0],
Integer.parseInt(field[1]), Double
.parseDouble(field[2]), field[3]);
// 置field[3]為空,以備下次輸入使用。
field[3] = "";
}
// 如果未輸入married,則field[3]為空,調(diào)用具有三個(gè)參數(shù)的Person構(gòu)造函數(shù)。
else {
people[i] = new Person(field[0],
Integer.parseInt(field[1]), Double
.parseDouble(field[2]));
}
}
// 將輸入的數(shù)據(jù)保存至“people.dat”文本文件中。
PrintWriter out = new PrintWriter(new BufferedWriter(
new FileWriter("people.dat")));
writeData(people, out);
// 關(guān)閉流。
out.close();
// 從文件“people.dat”讀取數(shù)據(jù)。
BufferedReader in = new BufferedReader(new FileReader("people.dat"));
Person[] inPeople = readData(in);
// 關(guān)閉流。
in.close();
// 輸出從文件中讀入的數(shù)據(jù)。
for (int i = 0; i inPeople.length; i++) {
System.out.println(inPeople[i]);
}
} catch (IOException exception) {
System.err.println("IOException");
}
}
// 將所有數(shù)據(jù)寫(xiě)入輸出流。
static void writeData(Person[] p, PrintWriter out) throws IOException {
// 寫(xiě)入記錄條數(shù),即人數(shù)。
out.println(p.length);
for (int i = 0; i p.length; i++) {
p[i].writeData(out);
}
}
// 將所有數(shù)據(jù)從輸入流中讀出。
static Person[] readData(BufferedReader in) throws IOException {
// 獲取記錄條數(shù),即人數(shù)。
int n = Integer.parseInt(in.readLine());
Person[] p = new Person[n];
for (int i = 0; i n; i++) {
p[i] = new Person();
p[i].readData(in);
}
return p;
}
}
class Person {
private String name;
private int age;
private double salary;
private String married;
public Person() {
}
public Person(String n, int a, double s) {
name = n;
age = a;
salary = s;
married = "F";
}
public Person(String n, int a, double s, String m) {
name = n;
age = a;
salary = s;
married = m;
}
public String getName() {
return name;
}
public int getAge() {
return age;
}
public double getSalary() {
return salary;
}
public String getMarried() {
return married;
}
// 設(shè)置輸出格式。
public String toString() {
return getClass().getName() + "[name=" + name + ",age=" + age
+ ",salary=" + salary + ",married=" + married + "]";
}
// 寫(xiě)入一條記錄,即一個(gè)人的數(shù)據(jù)到輸出流。
public void writeData(PrintWriter out) throws IOException {
// 格式化輸出。
out.println(name + ":" + age + ":" + salary + ":" + married);
}
// 從輸入流讀入一條記錄,即一個(gè)人的數(shù)據(jù)。
public void readData(BufferedReader in) throws IOException {
String s = in.readLine();
StringTokenizer t = new StringTokenizer(s, ":");
name = t.nextToken();
age = Integer.parseInt(t.nextToken());
salary = Double.parseDouble(t.nextToken());
married = t.nextToken();
}
}
package IO;
import java.io.IOException;
public class FileStdRead {
public static void main(String[] args) throws IOException {
int b = 0;
char c = ' ';
System.out.println("請(qǐng)輸入:");
while (c != 'q') {
int a = System.in.read();
c = (char) a;
b++;
System.out.println((char) a);
}
System.err.print("counted\t" + b + "\ttotalbytes.");
}
}
//讀取輸入的數(shù)據(jù),直到數(shù)據(jù)中有Q這個(gè)字母然
package IO;
import java.io.*;
public class IOStreamExample {
public static void main(String[] args) throws IOException {
// 1. 讀入一行數(shù)據(jù):
BufferedReader in = new BufferedReader(new FileReader(
"FileStdRead.java"));
String s, s2 = new String();
while ((s = in.readLine()) != null) {
s2 += s + "\n";
}
in.close();
BufferedReader stdin = new BufferedReader(new InputStreamReader(
System.in));
System.out.print("Enter a line:");
System.out.println(stdin.readLine());
// 2. 從內(nèi)存中讀入
StringReader in2 = new StringReader(s2);
int c;
while ((c = in2.read()) != -1) {
System.out.print((char) c);
}
// 3. 格式化內(nèi)存輸入
try {
DataInputStream in3 = new DataInputStream(new ByteArrayInputStream(
s2.getBytes()));
while (true) {
System.out.print((char) in3.readByte());
}
} catch (EOFException e) {
System.err.println("End of stream");
}
// 4. 文件輸入
try {
BufferedReader in4 = new BufferedReader(new StringReader(s2));
PrintWriter out1 = new PrintWriter(new BufferedWriter(
new FileWriter("IODemo.out")));
int lineCount = 1;
while ((s = in4.readLine()) != null) {
out1.println(lineCount++ + ": " + s);
}
out1.close();
} catch (EOFException e) {
System.err.println("End of stream");
}
// 5. 接收和保存數(shù)據(jù)
try {
DataOutputStream out2 = new DataOutputStream(
new BufferedOutputStream(new FileOutputStream("Data.txt")));
out2.writeDouble(3.14159);
out2.writeUTF("That was pi");
out2.writeDouble(1.41413);
out2.writeUTF("Square root of 2");
out2.close();
DataInputStream in5 = new DataInputStream(new BufferedInputStream(
new FileInputStream("Data.txt")));
System.out.println(in5.readDouble());
System.out.println(in5.readUTF());
System.out.println(in5.readDouble());
System.out.println(in5.readUTF());
} catch (EOFException e) {
throw new RuntimeException(e);
}
// 6. 隨機(jī)讀取文件內(nèi)容
RandomAccessFile rf = new RandomAccessFile("rtest.dat", "rw");
for (int i = 0; i 10; i++) {
rf.writeDouble(i * 1.414);
}
rf.close();
rf = new RandomAccessFile("rtest.dat", "rw");
rf.seek(5 * 8);
rf.writeDouble(47.0001);
rf.close();
rf = new RandomAccessFile("rtest.dat", "r");
for (int i = 0; i 10; i++) {
System.out.println("Value " + i + ": " + rf.readDouble());
}
rf.close();
}
}
package IO;
import java.io.*;
/**
* p
* Title: JAVA進(jìn)階訣竅
* /p
*
* @author 張峰
* @version 1.0
*/
public class MakeDirectoriesExample {
private static void fileattrib(File f) {
System.out.println("絕對(duì)路徑: " + f.getAbsolutePath() + "\n 可讀屬性: "
+ f.canRead() + "\n 可定屬性: " + f.canWrite() + "\n 文件名: "
+ f.getName() + "\n 父目錄: " + f.getParent() + "\n 當(dāng)前路徑: "
+ f.getPath() + "\n 文件長(zhǎng)度: " + f.length() + "\n 最后更新日期: "
+ f.lastModified());
if (f.isFile()) {
System.out.println("輸入的是一個(gè)文件");
} else if (f.isDirectory()) {
System.out.println("輸入的是一個(gè)目錄");
}
}
public static void main(String[] args) {
if (args.length 1) {
args = new String[3];
}
args[0] = "d";
args[1] = "test1.txt";
args[2] = "test2.txt";
File old = new File(args[1]), rname = new File(args[2]);
old.renameTo(rname);
fileattrib(old);
fileattrib(rname);
int count = 0;
boolean del = false;
if (args[0].equals("d")) {
count++;
del = true;
}
count--;
while (++count args.length) {
File f = new File(args[count]);
if (f.exists()) {
System.out.println(f + " 文件己經(jīng)存在");
if (del) {
System.out.println("刪除文件" + f);
f.delete();
}
} else { // 如果文件不存在
if (!del) {
f.mkdirs();
System.out.println("創(chuàng)建文件: " + f);
}
}
fileattrib(f);
}
}
}
磁盤(pán)IO的速度在那里了,就算你再多的線程,也繞不過(guò)IO瓶頸。不是說(shuō)多線程不能提高效率,這個(gè)要看你項(xiàng)目的性能瓶頸在哪里。 IO密集型,沒(méi)必要多線程,容易弄巧成拙。建議Cache,某些文件系統(tǒng)在順序讀或?qū)懘疟P(pán)時(shí)速度相當(dāng)快,如果恰好文件是順序存儲(chǔ)在磁盤(pán)上的,建議先盡量讀進(jìn)內(nèi)存,再一次性寫(xiě)出去。其他什么磁盤(pán)內(nèi)存通道之類(lèi)的底層技術(shù)就不是Java能左右的了。
package IO;
import java.io.*;
public class FileDirectoryDemo {
public static void main(String[] args) {
// 如果沒(méi)有指定參數(shù),則缺省為當(dāng)前目錄。
if (args.length == 0) {
args = new String[] { "." };
}
try {
// 新建指定目錄的File對(duì)象。
File currentPath = new File(args[0]);
// 在指定目錄新建temp目錄的File對(duì)象。
File tempPath = new File(currentPath, "temp");
// 用“tempPath”對(duì)象在指定目錄下創(chuàng)建temp目錄。
tempPath.mkdir();
// 在temp目錄下創(chuàng)建兩個(gè)文件。
File temp1 = new File(tempPath, "temp1.txt");
temp1.createNewFile();
File temp2 = new File(tempPath, "temp2.txt");
temp2.createNewFile();
// 遞歸顯示指定目錄的內(nèi)容。
System.out.println("顯示指定目錄的內(nèi)容");
listSubDir(currentPath);
// 更改文件名“temp1.txt”為“temp.txt”。
File temp1new = new File(tempPath, "temp.txt");
temp1.renameTo(temp1new);
// 遞歸顯示temp子目錄的內(nèi)容。
System.out.println("更改文件名后,顯示temp子目錄的內(nèi)容");
listSubDir(tempPath);
// 刪除文件“temp2.txt”。
temp2.delete();
// 遞歸顯示temp子目錄的內(nèi)容。
System.out.println("刪除文件后,顯示temp子目錄的內(nèi)容");
listSubDir(tempPath);
} catch (IOException e) {
System.err.println("IOException");
}
}
// 遞歸顯示指定目錄的內(nèi)容。
static void listSubDir(File currentPath) {
// 取得指定目錄的內(nèi)容列表。
String[] fileNames = currentPath.list();
try {
for (int i = 0; i fileNames.length; i++) {
File f = new File(currentPath.getPath(), fileNames[i]);
// 如果是目錄,則顯示目錄名后,遞歸調(diào)用,顯示子目錄的內(nèi)容。
if (f.isDirectory()) {
// 以規(guī)范的路徑格式顯示目錄。
System.out.println(f.getCanonicalPath());
// 遞歸調(diào)用,顯示子目錄。
listSubDir(f);
}
// 如果是文件,則顯示文件名,不包含路徑信息。
else {
System.out.println(f.getName());
}
}
} catch (IOException e) {
System.err.println("IOException");
}
}
}
package IO;
import java.io.*;
public class FileExample {
public FileExample() {
super();
}
public static void main(String[] args) {
try {
String outfile = "demoout.xml";
String infile = "demoin.xml";
/**
* 用FileOutputStream定義一個(gè)輸入流文件,然后用BuferedOutputStream調(diào)用FileOutputStream對(duì)象生成一個(gè)緩沖輸出流
然后用DataOutputStream調(diào)用BuferedOutputStream對(duì)象生成數(shù)據(jù)格式化輸出流
*/
DataOutputStream dt=new DataOutputStream(new BufferedOutputStream(new FileOutputStream(outfile)));
BufferedWriter NewFile = new BufferedWriter(new OutputStreamWriter(dt, "GBK"));
// 對(duì)中文的處理
// 定義一個(gè)輸入流
DataInputStream rafFile1 = new DataInputStream(new BufferedInputStream(new FileInputStream(infile)));
// 定義一個(gè)輸入緩沖
BufferedReader rafFile = new BufferedReader(new InputStreamReader(rafFile1, "GBK"));
String xmlcontent = "";
char tag = 0;// 文件友字符0結(jié)束
while (tag != (char) (-1)) {
xmlcontent = xmlcontent + tag + rafFile.readLine() + '\n';
tag = (char) rafFile.read();
}
NewFile.write(xmlcontent);
NewFile.flush();
NewFile.close();
rafFile.close();
System.gc();
} catch (NullPointerException exc) {
exc.printStackTrace();
} catch (java.lang.IndexOutOfBoundsException outb) {
System.out.println(outb.getMessage());
outb.printStackTrace();
} catch (FileNotFoundException fex) {
System.out.println("fex" + fex.getMessage());
} catch (IOException iex) {
System.out.println("iex" + iex.getMessage());
}
}
}
package IO;
import java.io.*;
public class FileRandomRW {
// 需要輸入的person數(shù)目。
public static int NUMBER = 3;
public static void main(String[] args) {
Persons[] people = new Persons[NUMBER];
people[0] = new Persons("張峰", 26, 2000, "N");
people[1] = new Persons("艷娜", 25, 50000, "Y");
people[2] = new Persons("李朋", 50, 7000, "F");
try {
DataOutputStream out = new DataOutputStream(new FileOutputStream(
"peoplerandom.dat"));
// 將人員數(shù)據(jù)保存至“peoplerandom.dat”二進(jìn)制文件中。
writeData(people, out);
// 關(guān)閉流。
out.close();
// 從二進(jìn)制文件“peoplerandom.dat”中逆序讀取數(shù)據(jù)。
RandomAccessFile inOut = new RandomAccessFile("peoplerandom.dat",
"rw");
Persons[] inPeople = readDataReverse(inOut);
// 輸出讀入的數(shù)據(jù)。
System.out.println("原始數(shù)據(jù):");
for (int i = 0; i inPeople.length; i++) {
System.out.println(inPeople[i]);
}
// 修改文件的第三條記錄。
inPeople[2].setSalary(4500);
// 將修改結(jié)果寫(xiě)入文件。
inPeople[2].writeData(inOut, 3);
// 關(guān)閉流。
inOut.close();
// 從文件中讀入的第三條記錄,并輸出,以驗(yàn)證修改結(jié)果。
RandomAccessFile in = new RandomAccessFile("peoplerandom.dat", "r");
Persons in3People = new Persons();
// 隨機(jī)讀第三條記錄。
in3People.readData(in, 3);
// 關(guān)閉流。
in.close();
System.out.println("修改后的記錄");
System.out.println(in3People);
} catch (IOException exception) {
System.err.println("IOException");
}
}
// 將數(shù)據(jù)寫(xiě)入輸出流。
static void writeData(Persons[] p, DataOutputStream out) throws IOException {
for (int i = 0; i p.length; i++) {
p[i].writeData(out);
}
}
// 將數(shù)據(jù)從輸入流中逆序讀出。
static Persons[] readDataReverse(RandomAccessFile in) throws IOException {
// 獲得記錄數(shù)目。
int record_num = (int) (in.length() / Persons.RECORD_LENGTH);
Persons[] p = new Persons[record_num];
// 逆序讀取。
for (int i = record_num - 1; i = 0; i--) {
p[i] = new Persons();
// 文件定位。
in.seek(i * Persons.RECORD_LENGTH);
p[i].readData(in, i + 1);
}
return p;
}
}
class Persons {
private String name;
private int age; // 4個(gè)字節(jié)
private double salary; // 8個(gè)字節(jié)
private String married;
public static final int NAME_LENGTH = 20; // 姓名長(zhǎng)度
public static final int MARRIED_LENGTH = 2; // 婚否長(zhǎng)度
public static final int RECORD_LENGTH = NAME_LENGTH * 2 + 4 + 8
+ MARRIED_LENGTH * 2;
public Persons() {
}
public Persons(String n, int a, double s) {
name = n;
age = a;
salary = s;
married = "F";
}
public Persons(String n, int a, double s, String m) {
name = n;
age = a;
salary = s;
married = m;
}
public String getName() {
return name;
}
public int getAge() {
return age;
}
public double getSalary() {
return salary;
}
public String getMarried() {
return married;
}
public String setName(String n) {
name = n;
return name;
}
public int setAge(int a) {
age = a;
return age;
}
public double setSalary(double s) {
salary = s;
return salary;
}
public String setMarried(String m) {
married = m;
return married;
}
// 設(shè)置輸出格式。
public String toString() {
return getClass().getName() + "[name=" + name + ",age=" + age
+ ",salary=" + salary + ",married=" + married + "]";
}
// 寫(xiě)入一條固定長(zhǎng)度的記錄,即一個(gè)人的數(shù)據(jù)到輸出流。
public void writeData(DataOutput out) throws IOException {
FixStringIO.writeFixString(name, NAME_LENGTH, out);
out.writeInt(age);
out.writeDouble(salary);
FixStringIO.writeFixString(married, MARRIED_LENGTH, out);
}
// 寫(xiě)入一條固定長(zhǎng)度的記錄到隨機(jī)讀取文件中。
private void writeData(RandomAccessFile out) throws IOException {
FixStringIO.writeFixString(name, NAME_LENGTH, out);
out.writeInt(age);
out.writeDouble(salary);
FixStringIO.writeFixString(married, MARRIED_LENGTH, out);
}
// 隨機(jī)寫(xiě)入一條固定長(zhǎng)度的記錄到輸出流的指定位置。
public void writeData(RandomAccessFile out, int n) throws IOException {
out.seek((n - 1) * RECORD_LENGTH);
writeData(out);
}
// 從輸入流隨機(jī)讀入一條記錄,即一個(gè)人的數(shù)據(jù)。
private void readData(RandomAccessFile in) throws IOException {
name = FixStringIO.readFixString(NAME_LENGTH, in);
age = in.readInt();
salary = in.readDouble();
married = FixStringIO.readFixString(MARRIED_LENGTH, in);
}
// 從輸入流隨機(jī)讀入指定位置的記錄。
public void readData(RandomAccessFile in, int n) throws IOException {
in.seek((n - 1) * RECORD_LENGTH);
readData(in);
}
}
// 對(duì)固定長(zhǎng)度字符串從文件讀出、寫(xiě)入文件
class FixStringIO {
// 讀取固定長(zhǎng)度的Unicode字符串。
public static String readFixString(int size, DataInput in)
throws IOException {
StringBuffer b = new StringBuffer(size);
int i = 0;
boolean more = true;
while (more i size) {
char ch = in.readChar();
i++;
if (ch == 0) {
more = false;
} else {
b.append(ch);
}
}
// 跳過(guò)剩余的字節(jié)。
in.skipBytes(2 * (size - i));
return b.toString();
}
// 寫(xiě)入固定長(zhǎng)度的Unicode字符串。
public static void writeFixString(String s, int size, DataOutput out)
throws IOException {
int i;
for (i = 0; i size; i++) {
char ch = 0;
if (i s.length()) {
ch = s.charAt(i);
}
out.writeChar(ch);
}
}
}
package IO;
import java.io.*;
import java.util.*;
public class FileRW {
// 需要輸入的person數(shù)目。
public static int NUMBER = 3;
public static void main(String[] args) {
Person[] people = new Person[NUMBER];
// 暫時(shí)容納輸入數(shù)據(jù)的臨時(shí)字符串?dāng)?shù)組。
String[] field = new String[4];
// 初始化field數(shù)組。
for (int i = 0; i 4; i++) {
field[i] = "";
}
// IO操作必須捕獲IO異常。
try {
// 用于對(duì)field數(shù)組進(jìn)行增加控制。
int fieldcount = 0;
// 先使用System.in構(gòu)造InputStreamReader,再構(gòu)造BufferedReader。
BufferedReader stdin = new BufferedReader(new InputStreamReader(
System.in));
for (int i = 0; i NUMBER; i++) {
fieldcount = 0;
System.out.println("The number " + (i + 1) + " person");
System.out
.println("Enter name,age,salary,married(optional),please separate fields by ':'");
// 讀取一行。
String personstr = stdin.readLine();
// 設(shè)置分隔符。
StringTokenizer st = new StringTokenizer(personstr, ":");
// 判斷是否還有分隔符可用。
while (st.hasMoreTokens()) {
field[fieldcount] = st.nextToken();
fieldcount++;
}
// 如果輸入married,則field[3]不為空,調(diào)用具有四個(gè)參數(shù)的Person構(gòu)造函數(shù)。
if (field[3] != "") {
people[i] = new Person(field[0],
Integer.parseInt(field[1]), Double
.parseDouble(field[2]), field[3]);
// 置field[3]為空,以備下次輸入使用。
field[3] = "";
}
// 如果未輸入married,則field[3]為空,調(diào)用具有三個(gè)參數(shù)的Person構(gòu)造函數(shù)。
else {
people[i] = new Person(field[0],
Integer.parseInt(field[1]), Double
.parseDouble(field[2]));
}
}
// 將輸入的數(shù)據(jù)保存至“people.dat”文本文件中。
PrintWriter out = new PrintWriter(new BufferedWriter(
new FileWriter("people.dat")));
writeData(people, out);
// 關(guān)閉流。
out.close();
// 從文件“people.dat”讀取數(shù)據(jù)。
BufferedReader in = new BufferedReader(new FileReader("people.dat"));
Person[] inPeople = readData(in);
// 關(guān)閉流。
in.close();
// 輸出從文件中讀入的數(shù)據(jù)。
for (int i = 0; i inPeople.length; i++) {
System.out.println(inPeople[i]);
}
} catch (IOException exception) {
System.err.println("IOException");
}
}
// 將所有數(shù)據(jù)寫(xiě)入輸出流。
static void writeData(Person[] p, PrintWriter out) throws IOException {
// 寫(xiě)入記錄條數(shù),即人數(shù)。
out.println(p.length);
for (int i = 0; i p.length; i++) {
p[i].writeData(out);
}
}
// 將所有數(shù)據(jù)從輸入流中讀出。
static Person[] readData(BufferedReader in) throws IOException {
// 獲取記錄條數(shù),即人數(shù)。
int n = Integer.parseInt(in.readLine());
Person[] p = new Person[n];
for (int i = 0; i n; i++) {
p[i] = new Person();
p[i].readData(in);
}
return p;
}
}
class Person {
private String name;
private int age;
private double salary;
private String married;
public Person() {
}
public Person(String n, int a, double s) {
name = n;
age = a;
salary = s;
married = "F";
}
public Person(String n, int a, double s, String m) {
name = n;
age = a;
salary = s;
married = m;
}
public String getName() {
return name;
}
public int getAge() {
return age;
}
public double getSalary() {
return salary;
}
public String getMarried() {
return married;
}
// 設(shè)置輸出格式。
public String toString() {
return getClass().getName() + "[name=" + name + ",age=" + age
+ ",salary=" + salary + ",married=" + married + "]";
}
// 寫(xiě)入一條記錄,即一個(gè)人的數(shù)據(jù)到輸出流。
public void writeData(PrintWriter out) throws IOException {
// 格式化輸出。
out.println(name + ":" + age + ":" + salary + ":" + married);
}
// 從輸入流讀入一條記錄,即一個(gè)人的數(shù)據(jù)。
public void readData(BufferedReader in) throws IOException {
String s = in.readLine();
StringTokenizer t = new StringTokenizer(s, ":");
name = t.nextToken();
age = Integer.parseInt(t.nextToken());
salary = Double.parseDouble(t.nextToken());
married = t.nextToken();
}
}
package IO;
import java.io.*;
public class IOStreamExample {
public static void main(String[] args) throws IOException {
// 1. 讀入一行數(shù)據(jù):
BufferedReader in = new BufferedReader(new FileReader(
"FileStdRead.java"));
String s, s2 = new String();
while ((s = in.readLine()) != null) {
s2 += s + "\n";
}
in.close();
BufferedReader stdin = new BufferedReader(new InputStreamReader(
System.in));
System.out.print("Enter a line:");
System.out.println(stdin.readLine());
// 2. 從內(nèi)存中讀入
StringReader in2 = new StringReader(s2);
int c;
while ((c = in2.read()) != -1) {
System.out.print((char) c);
}
// 3. 格式化內(nèi)存輸入
try {
DataInputStream in3 = new DataInputStream(new ByteArrayInputStream(
s2.getBytes()));
while (true) {
System.out.print((char) in3.readByte());
}
} catch (EOFException e) {
System.err.println("End of stream");
}
// 4. 文件輸入
try {
BufferedReader in4 = new BufferedReader(new StringReader(s2));
PrintWriter out1 = new PrintWriter(new BufferedWriter(
new FileWriter("IODemo.out")));
int lineCount = 1;
while ((s = in4.readLine()) != null) {
out1.println(lineCount++ + ": " + s);
}
out1.close();
} catch (EOFException e) {
System.err.println("End of stream");
}
// 5. 接收和保存數(shù)據(jù)
try {
DataOutputStream out2 = new DataOutputStream(
new BufferedOutputStream(new FileOutputStream("Data.txt")));
out2.writeDouble(3.14159);
out2.writeUTF("That was pi");
out2.writeDouble(1.41413);
out2.writeUTF("Square root of 2");
out2.close();
DataInputStream in5 = new DataInputStream(new BufferedInputStream(
new FileInputStream("Data.txt")));
System.out.println(in5.readDouble());
System.out.println(in5.readUTF());
System.out.println(in5.readDouble());
System.out.println(in5.readUTF());
} catch (EOFException e) {
throw new RuntimeException(e);
}
// 6. 隨機(jī)讀取文件內(nèi)容
RandomAccessFile rf = new RandomAccessFile("rtest.dat", "rw");
for (int i = 0; i 10; i++) {
rf.writeDouble(i * 1.414);
}
rf.close();
rf = new RandomAccessFile("rtest.dat", "rw");
rf.seek(5 * 8);
rf.writeDouble(47.0001);
rf.close();
rf = new RandomAccessFile("rtest.dat", "r");
for (int i = 0; i 10; i++) {
System.out.println("Value " + i + ": " + rf.readDouble());
}
rf.close();
}
}
package IO;
import java.io.*;
/**
* p
* Title: JAVA進(jìn)階訣竅
* /p
*
* @author 張峰
* @version 1.0
*/
public class MakeDirectoriesExample {
private static void fileattrib(File f) {
System.out.println("絕對(duì)路徑: " + f.getAbsolutePath() + "\n 可讀屬性: "
+ f.canRead() + "\n 可定屬性: " + f.canWrite() + "\n 文件名: "
+ f.getName() + "\n 父目錄: " + f.getParent() + "\n 當(dāng)前路徑: "
+ f.getPath() + "\n 文件長(zhǎng)度: " + f.length() + "\n 最后更新日期: "
+ f.lastModified());
if (f.isFile()) {
System.out.println("輸入的是一個(gè)文件");
} else if (f.isDirectory()) {
System.out.println("輸入的是一個(gè)目錄");
}
}
public static void main(String[] args) {
if (args.length 1) {
args = new String[3];
}
args[0] = "d";
args[1] = "test1.txt";
args[2] = "test2.txt";
File old = new File(args[1]), rname = new File(args[2]);
old.renameTo(rname);
fileattrib(old);
fileattrib(rname);
int count = 0;
boolean del = false;
if (args[0].equals("d")) {
count++;
del = true;
}
count--;
while (++count args.length) {
File f = new File(args[count]);
if (f.exists()) {
System.out.println(f + " 文件己經(jīng)存在");
if (del) {
System.out.println("刪除文件" + f);
f.delete();
}
} else { // 如果文件不存在
if (!del) {
f.mkdirs();
System.out.println("創(chuàng)建文件: " + f);
}
}
fileattrib(f);
}
}
}
文章標(biāo)題:javaio密集代碼,javaio流代碼
當(dāng)前鏈接:http://chinadenli.net/article34/heeese.html
成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供面包屑導(dǎo)航、靜態(tài)網(wǎng)站、網(wǎng)站收錄、軟件開(kāi)發(fā)、關(guān)鍵詞優(yōu)化、商城網(wǎng)站
聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請(qǐng)盡快告知,我們將會(huì)在第一時(shí)間刪除。文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如需處理請(qǐng)聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時(shí)需注明來(lái)源: 創(chuàng)新互聯(lián)