土嘎嘎的粉丝们大家好,代码如下:
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.Reader;
import java.io.Writer;
public static void main(String args[]) throws Exception{// 异常抛出,不处理
File f1= new File("c:" + File.separator + "a.txt") ;// 声明File对象
Reader input = null ;// 准备好一个输入的对象
Writer out = null ;
input = new FileReader(f1) ;// 通过对象多态性,进行实例化
int temp = 0 ;// 接收每一个内容
int len = 0 ;// 读取内容
while((temp=input.read())!=-1){
out.write(temp) ;
c[len] = (char)temp ;
len++ ;
}
input.close() ;// 关闭输出流
out.close() ;
System.out.println("内容为:" + new String(c,0,len)) ;// 把字符数组变为字符串输出
};
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
说明:文件加密
加密方法:三重DES加密
加密过程:对选中的文件加密后在同文件夹下生成一个增加了".tdes"
扩展名的加密文件
解密过程:对选中的加密文件(必须有".tdes"扩展名)进行解密
*/
public class FileEncrypter extends JFrame{
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.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,"请选择文件!","提示",JOptionPane.OK_OPTION);
});
JButton jbD = new JButton("解密");
c.add(jbD);
jbD.addActionListener(new ActionListener(){
decrypt(file.getAbsoluteFile(),pp.getKey());
加密函数
输入:
其中:
输出:
对输入的文件加密后,保存到同一文件夹下增加了".tdes"扩展名的文件中.
private void encrypt(File fileIn,String sKey){
try{
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(
String fileOut = fileIn.getPath() + ".tdes";
FileOutputStream fos = new FileOutputStream(fileOut);
for(int i = 0;iBYTOUT.LENGTH;I++){
fos.write((int)bytOut[i]);
fos.close();
this,"加密成功!","提示",JOptionPane.OK_OPTION);
}else
}catch(Exception e){
e.printStackTrace();
解密函数
对输入的文件解密后,保存到用户指定的文件中.
private void decrypt(File fileIn,String sKey){
String strPath = fileIn.getPath();
else{
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[] bytOut = decryptByDES(decryptByDES(
File fileOut = chooser.getSelectedFile();
fileOut.createNewFile();
this,"解密成功!","提示",JOptionPane.OK_OPTION);
this,"解密失败,请核对密码!","提示",JOptionPane.OK_OPTION);
用DES方法加密输入的字节
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方法解密输入的字节
private byte[] decryptByDES(byte[] bytE,byte[] bytKey) throws Exception{
cip.init(Cipher.DECRYPT_MODE,sk);
return cip.doFinal(bytE);
输入密码的字符形式,返回字节数组形式.
private byte[] getKeyByStr(String str){
for(int i=0;iSTR.LENGTH()
Integer itg =
bRet[i] = itg.byteValue();
return bRet;
输入: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=="A".charAt(0)) iRet = 10;
if(chr=="B".charAt(0)) iRet = 11;
return iRet;
文件选择组件.
class FilePanel extends JPanel{
FilePanel(String str){
JLabel label = new JLabel(str);
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;
int ret = chooser.showOpenDialog(cmpt);
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){
JButton chooseButton = new JButton("随机产生");
public String getKey(){
KeyGenerator kg = KeyGenerator.getInstance("DES");
Key ke = kg.generateKey();
byte[] bytK1 = ke.getEncoded();
ke = kg.generateKey();
private String getByteStr(byte[] byt){
String strRet = "";
for(int i=0;iBYT.LENGTH;I++){
//System.out.println(byt[i]);
return strRet;
private String getHexValue(int s){
String sRet=null;
switch (s){
case 0: sRet = "0";break;
case 1: sRet = "1";break;
case 10: sRet = "A";break;
case 11: sRet = "B";break;
return sRet;
用BufferedReader就可以了
{
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;
public class FileDirectoryDemo {
public static void main(String[] args) {
// 如果没有指定参数,则缺省为当前目录.
if (args.length == 0) {
args = new String[] { "." };
try {
// 新建指定目录的File对象.
File currentPath = new File(args[0]);
// 在指定目录新建temp目录的File对象.
File tempPath = new File(currentPath, "temp");
// 用"tempPath"对象在指定目录下创建temp目录.
tempPath.mkdir();
// 在temp目录下创建两个文件.
File temp1 = new File(tempPath, "temp1.txt");
temp1.createNewFile();
// 递归显示指定目录的内容.
System.out.println("显示指定目录的内容");
listSubDir(currentPath);
// 更改文件名"temp1.txt"为"temp.txt".
File temp1new = new File(tempPath, "temp.txt");
temp1.renameTo(temp1new);
// 递归显示temp子目录的内容.
System.out.println("更改文件名后,显示temp子目录的内容");
listSubDir(tempPath);
System.out.println("删除文件后,显示temp子目录的内容");
} catch (IOException e) {
System.err.println("IOException");
static void listSubDir(File currentPath) {
// 取得指定目录的内容列表.
String[] fileNames = currentPath.list();
for (int i = 0; i fileNames.length; i++) {
File f = new File(currentPath.getPath(), fileNames[i]);
// 如果是目录,则显示目录名后,递归调用,显示子目录的内容.
if (f.isDirectory()) {
// 以规范的路径格式显示目录.
System.out.println(f.getCanonicalPath());
// 递归调用,显示子目录.
listSubDir(f);
// 如果是文件,则显示文件名,不包含路径信息.
else {
System.out.println(f.getName());
public class FileExample {
public FileExample() {
super();// 调用父类的构造函数
String outfile = "demoout.xml";
// 定义了一个变量, 用于标识输出文件
String infile = "demoin.xml";
// 定义了一个变量, 用于标识输入文件
DataOutputStream dt = new DataOutputStream(
new BufferedOutputStream(new FileOutputStream(outfile)));
* 用FileOutputStream定义一个输入流文件,
* 然后用BuferedOutputStream调用FileOutputStream对象生成一个缓冲输出流
* 然后用DataOutputStream调用BuferedOutputStream对象生成数据格式化输出流
BufferedWriter NewFile = new BufferedWriter(new OutputStreamWriter(
dt, "gbk"));// 对中文的处理
DataInputStream rafFile1 = new DataInputStream(
new BufferedInputStream(new FileInputStream(infile)));
*用FileInputStream定义一个输入流文件,
* 然后用BuferedInputStream调用FileInputStream对象生成一个缓冲输出流
* ,其后用DataInputStream中调用BuferedInputStream对象生成数据格式化输出流
BufferedReader rafFile = new BufferedReader(new InputStreamReader(
rafFile1, "gbk"));// 对中文的处理
String xmlcontent = "";
char tag = 0;// 文件用字符零结束
while (tag != (char) (-1)) {
xmlcontent = xmlcontent + tag + rafFile.readLine() + '\n';
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());
public class FileRandomRW {
// 需要输入的person数目.
Persons[] people = new Persons[NUMBER];
DataOutputStream out = new DataOutputStream(new FileOutputStream(
"peoplerandom.dat"));
// 将人员数据保存至"peoplerandom.dat"二进制文件中.
writeData(people, out);
// 关闭流.
out.close();
// 从二进制文件"peoplerandom.dat"中逆序读取数据.
RandomAccessFile inOut = new RandomAccessFile("peoplerandom.dat",
"rw");
Persons[] inPeople = readDataReverse(inOut);
// 输出读入的数据.
System.out.println("原始数据:");
for (int i = 0; i inPeople.length; i++) {
System.out.println(inPeople[i]);
// 修改文件的第三条记录.
// 将修改结果写入文件.
inOut.close();
// 从文件中读入的第三条记录,并输出,以验证修改结果.
RandomAccessFile in = new RandomAccessFile("peoplerandom.dat", "r");
// 随机读第三条记录.
in.close();
System.out.println("修改后的记录");
} catch (IOException exception) {
// 将数据写入输出流.
static void writeData(Persons[] p, DataOutputStream out) throws IOException {
for (int i = 0; i p.length; i++) {
p[i].writeData(out);
// 将数据从输入流中逆序读出.
static Persons[] readDataReverse(RandomAccessFile in) throws IOException {
// 获得记录数目.
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 String married;
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) {
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) {
public int setAge(int a) {
public double setSalary(double s) {
public String setMarried(String m) {
// 设置输出格式.
public String toString() {
return getClass().getName() + "[name=" + name + ",age=" + age
+ ",salary=" + salary + ",married=" + married + "]";
// 写入一条固定长度的记录,即一个人的数据到输出流.
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);
// 写入一条固定长度的记录到随机读取文件中.
private void writeData(RandomAccessFile out) throws IOException {
// 随机写入一条固定长度的记录到输出流的指定位置.
public void writeData(RandomAccessFile out, int n) throws IOException {
out.seek((n - 1) * RECORD_LENGTH);
writeData(out);
// 从输入流随机读入一条记录,即一个人的数据.
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);
// 从输入流随机读入指定位置的记录.
public void readData(RandomAccessFile in, int n) throws IOException {
in.seek((n - 1) * RECORD_LENGTH);
readData(in);
// 对固定长度字符串从文件读出、写入文件
class FixStringIO {
// 读取固定长度的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);
// 跳过剩余的字节.
return b.toString();
// 写入固定长度的Unicode字符串.
public static void writeFixString(String s, int size, DataOutput out)
int i;
for (i = 0; i size; i++) {
char ch = 0;
if (i s.length()) {
ch = s.charAt(i);
out.writeChar(ch);
import java.util.*;
public class FileRW {
Person[] people = new Person[NUMBER];
// 暂时容纳输入数据的临时字符串数组.
// 初始化field数组.
field[i] = "";
// IO操作必须捕获IO异常.
// 用于对field数组进行增加控制.
int fieldcount = 0;
// 先使用System.in构造InputStreamReader,再构造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();
// 设置分隔符.
StringTokenizer st = new StringTokenizer(personstr, ":");
// 判断是否还有分隔符可用.
while (st.hasMoreTokens()) {
field[fieldcount] = st.nextToken();
fieldcount++;
people[i] = new Person(field[0],
Integer.parseInt(field[1]), Double
// 将输入的数据保存至"people.dat"文本文件中.
PrintWriter out = new PrintWriter(new BufferedWriter(
new FileWriter("people.dat")));
// 从文件"people.dat"读取数据.
BufferedReader in = new BufferedReader(new FileReader("people.dat"));
Person[] inPeople = readData(in);
// 输出从文件中读入的数据.
// 将所有数据写入输出流.
static void writeData(Person[] p, PrintWriter out) throws IOException {
// 写入记录条数,即人数.
out.println(p.length);
// 将所有数据从输入流中读出.
static Person[] readData(BufferedReader in) throws IOException {
// 获取记录条数,即人数.
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);
class Person {
private int age;
private double salary;
public Person() {
public Person(String n, int a, double s) {
public Person(String n, int a, double s, String m) {
// 写入一条记录,即一个人的数据到输出流.
public void writeData(PrintWriter out) throws IOException {
// 格式化输出.
out.println(name + ":" + age + ":" + salary + ":" + married);
// 从输入流读入一条记录,即一个人的数据.
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();
import java.io.IOException;
public class FileStdRead {
public static void main(String[] args) throws IOException {
int b = 0;
char c = ' ';
System.out.println("请输入:");
while (c != 'q') {
int a = System.in.read();
c = (char) a;
b++;
System.out.println((char) a);
System.err.print("counted\t" + b + "\ttotalbytes.");
//读取输入的数据,直到数据中有Q这个字母然
public class IOStreamExample {
// 1. 读入一行数据:
BufferedReader in = new BufferedReader(new FileReader(
"FileStdRead.java"));
while ((s = in.readLine()) != null) {
System.out.print("Enter a line:");
System.out.println(stdin.readLine());
int c;
System.out.print((char) c);
while (true) {
} catch (EOFException e) {
System.err.println("End of stream");
PrintWriter out1 = new PrintWriter(new BufferedWriter(
new FileWriter("IODemo.out")));
int lineCount = 1;
out1.println(lineCount++ + ": " + s);
out1.close();
new BufferedOutputStream(new FileOutputStream("Data.txt")));
new FileInputStream("Data.txt")));
throw new RuntimeException(e);
RandomAccessFile rf = new RandomAccessFile("rtest.dat", "rw");
for (int i = 0; i 10; i++) {
rf.close();
rf = new RandomAccessFile("rtest.dat", "rw");
rf = new RandomAccessFile("rtest.dat", "r");
System.out.println("Value " + i + ": " + rf.readDouble());
* p
* Title: JAVA进阶诀窍
* /p
*
* @author 张峰
* @version 1.0
public class MakeDirectoriesExample {
private static void fileattrib(File f) {
System.out.println("绝对路径: " + f.getAbsolutePath() + "\n 可读属性: "
+ f.canRead() + "\n 可定属性: " + f.canWrite() + "\n 文件名: "
+ f.getName() + "\n 父目录: " + f.getParent() + "\n 当前路径: "
+ f.getPath() + "\n 文件长度: " + f.length() + "\n 最后更新日期: "
+ f.lastModified());
if (f.isFile()) {
System.out.println("输入的是一个文件");
} else if (f.isDirectory()) {
System.out.println("输入的是一个目录");
if (args.length 1) {
args[0] = "d";
args[1] = "test1.txt";
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 + " 文件己经存在");
if (del) {
System.out.println("删除文件" + f);
f.delete();
} else { // 如果文件不存在
if (!del) {
f.mkdirs();
System.out.println("创建文件: " + f);
fileattrib(f);
磁盘IO的速度在那里了,就算你再多的线程,也绕不过IO瓶颈.不是说多线程不能提高效率,这个要看你项目的性能瓶颈在哪里. IO密集型,没必要多线程,容易弄巧成拙.建议Cache,某些文件系统在顺序读或写磁盘时速度相当快,如果恰好文件是顺序存储在磁盘上的,建议先尽量读进内存,再一次性写出去.其他什么磁盘内存通道之类的底层技术就不是Java能左右的了.
super();
* 用FileOutputStream定义一个输入流文件,然后用BuferedOutputStream调用FileOutputStream对象生成一个缓冲输出流
然后用DataOutputStream调用BuferedOutputStream对象生成数据格式化输出流
DataOutputStream dt=new DataOutputStream(new BufferedOutputStream(new FileOutputStream(outfile)));
BufferedWriter NewFile = new BufferedWriter(new OutputStreamWriter(dt, "GBK"));
// 对中文的处理
// 定义一个输入流
DataInputStream rafFile1 = new DataInputStream(new BufferedInputStream(new FileInputStream(infile)));
// 定义一个输入缓冲
BufferedReader rafFile = new BufferedReader(new InputStreamReader(rafFile1, "GBK"));
char tag = 0;// 文件友字符0结束
tag = (char) rafFile.read();
NewFile.flush();
System.gc();
以上就是土嘎嘎小编为大家整理的javaio密集代码相关主题介绍,如果您觉得小编更新的文章只要能对粉丝们有用,就是我们最大的鼓励和动力,不要忘记讲本站分享给您身边的朋友哦!!