import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
class Cipher3{
public
static int initial = 3;
String Plain = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
String Cipher;
Cipher3()
{
generateCipher();
}
int getini()
{
return this.initial;
}
void generateCipher()
{
this.Cipher = this.Plain.substring(this.initial);
this.Cipher = this.Cipher + this.Plain.substring(0, this.initial - 1);
}
// for eclipse default folder : File file = new File("src/accounts.txt");
void encode( String input, String output ) throws IOException
{
// read io
String line;
File file = new File(input);
FileReader fr = new FileReader(file);
BufferedReader inFile = new BufferedReader(fr);
line = inFile.readLine();
// write io
File outf = new File(output);
if (outf.exists()) {
// System.out.println("file exit");
}
else {
// System.out.println("file does not exit, creating");
if (outf.createNewFile()) {
// System.out.println("succeed in creating");
}
else {
System.out.println("fail to create file");
}
}
BufferedWriter outFile = new BufferedWriter(new FileWriter(outf));
while (line != null)
{
// deal with line
String outstr = "";
for ( int i = 0; i < line.length(); i ++ )
{
String temp = line.substring(i, i+1);
int index = this.Plain.indexOf( temp );
if (index != -1)
{
outstr += this.Cipher.substring(index, index + 1);
}
else
{
outstr += temp;
}
}
outFile.write(outstr);
outFile.newLine();
line = inFile.readLine();
}
// read io close
inFile.close();
// write io close
outFile.close();
}
void decode( String input, String output ) throws IOException
{
// read io
String line;
File file = new File(input);
FileReader fr = new FileReader(file);
BufferedReader inFile = new BufferedReader(fr);
line = inFile.readLine();
// write io
File outf = new File(output);
if (outf.exists()) {
// System.out.println("file exit");
}
else {
// System.out.println("file does not exit, creating");
if (outf.createNewFile()) {
// System.out.println("succeed in creating");
}
else {
System.out.println("fail to create file");
}
}
BufferedWriter outFile = new BufferedWriter(new FileWriter(outf));
while (line != null)
{
// deal with line
String outstr = "";
for ( int i = 0; i < line.length(); i ++ )
{
String temp = line.substring(i, i+1);
int index = this.Cipher.indexOf( temp );
if (index != -1)
{
outstr += this.Plain.substring(index, index + 1);
}
else
{
outstr += temp;
}
}
outFile.write(outstr);
outFile.newLine();
line = inFile.readLine();
}
// read io close
inFile.close();
// write io close
outFile.close();
}
}
参考: http://sharewind.javaeye.com/blog/227538