0

学校のプロジェクトの基本的な暗号化プログラムに取り組んでおり、簡単に交換できるキーが必要です。現状では、複数のメソッドを持つ暗号化クラスと復号化クラスがあります。それらの方法の 1 つは、ファイルに出力したいキーです。これら 2 つのクラス (キーを除く) に多くの変更を加える予定なので、その 1 つのメソッドだけをファイルに出力できるようにしたいと考えています。また、再度ロードできるようにする必要があります。これを行う簡単な方法はありますか?

4

2 に答える 2

0

保存する文字列配列があるとコメントしたように、Javaシリアライゼーションを使用できます。次のようなことができます。

// save object to file
ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(new File("/tmp/file")));
oos.writeObject(myArray); // where myArray is String[]

// load object from file
ObjectInputStream ois = new ObjectInputStream(new FileInputStream(new File("/tmp/file")));
String[] read = (String[]) ois.readObject();

実際の例;)、アプリケーションの実行で受け取った引数を保存します。

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.Arrays;

public class TestSerialization {

    public static void main(final String[] array) throws FileNotFoundException, IOException, ClassNotFoundException {
        // save object to file
        ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(new File("/tmp/file")));
        oos.writeObject(array); // where myArray is String[]

        // load object from file
        ObjectInputStream ois = new ObjectInputStream(new FileInputStream(new File("/tmp/file")));
        String[] read = (String[]) ois.readObject();

        System.out.println(Arrays.toString(read));
    }

}
于 2012-06-29T15:27:15.573 に答える
0

ユーザー Speath によって指摘されたシリアル化は、私が見つけた非常に優れたアプローチです。

ファイルに書き込む内容をより厳選したい場合は、単純なファイル I/O を使用して、次のようにファイルに書き込むことができます。

FileWriter クラスを使用してファイル システムに新しいファイルを作成し、BufferedWriter を使用して I/O ストリームを開始して、このファイルに書き込みます。

// create a new file with specified file name
FileWriter fw = new FileWriter("myFile.log");

// create the IO strem on that file
BufferedWriter bw = new BufferedWriter(fw);

// write a string into the IO stream
bw.out("my log entry");

// don't forget to close the stream!
bw.close();

IO 例外をキャッチするには、すべてを try/catch で囲む必要があります。

お役に立てれば。

于 2012-06-29T15:33:06.247 に答える