17

ファイルを圧縮および解凍するプログラムを実装しようとしています。私がやりたいのは、ファイル(fileName.fileExtension)をfileName.zipという名前で圧縮し、解凍時に再びfileName.fileExtensionに変更することだけです。

4

7 に答える 7

14

これは、ファイルの名前を変更したり、拡張子を変更したりする方法です。

public static void modify(File file) 
    {
        int index = file.getName().lastIndexOf(".");
        //print filename
        //System.out.println(file.getName().substring(0, index));
        //print extension
        //System.out.println(file.getName().substring(index));
        String ext = file.getName().substring(index);
        //use file.renameTo() to rename the file
        file.renameTo(new File("Newname"+ext));
    }

edit : John の方法では、ファイルの名前を変更します (拡張子はそのままです)。拡張子を変更するには、次のようにします。

public static File changeExtension(File f, String newExtension) {
  int i = f.getName().lastIndexOf('.');
  String name = f.getName().substring(0,i);
  return new File(f.getParent(), name + newExtension);
}

これは、ファイル名の最後の拡張子、つまり. したがって、名前が a で始まる Linux の隠しファイルで問題なく動作します。これ は非常に安全です。 File コンストラクターが最初に評価されます。.gzarchive.tar.gz.getParent()null

面白い出力が得られる唯一のケースは、システム ルート自体を表す File を渡す場合です。この場合、nullパス文字列の残りの前に が追加されます。

于 2012-08-31T06:36:50.973 に答える
8

試してみてください:

File file  = new File("fileName.zip"); // handler to your ZIP file
File file2 = new File("fileName.fileExtension"); // destination dir of your file
boolean success = file.renameTo(file2);
if (success) {
    // File has been renamed
}
于 2012-08-31T06:20:20.153 に答える
0

前述の @hsz と同じロジックで、代わりに単純に置換を使用します。

File file  = new File("fileName.fileExtension"); // creating object of File 
String str = file.getPath().replace(".fileExtension", ".zip"); // replacing extension to another 
file.renameTo(new File(str)); 
于 2019-06-14T01:29:25.370 に答える