Skip to content

Instantly share code, notes, and snippets.

@AoEiuV020
Created March 9, 2023 15:00
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save AoEiuV020/668ba0ab3ae96db95ecfd07fe04dec21 to your computer and use it in GitHub Desktop.
Save AoEiuV020/668ba0ab3ae96db95ecfd07fe04dec21 to your computer and use it in GitHub Desktop.
java使用特定编码做文件名读写文件
import com.sun.jna.*;
public class JnaFileTest {
private static final String fileName = "我一定会回来的";
private static final String fileContent = "随便写点什么都一样,";
public static void main(String args[]) throws Exception {
JNAApiInterface jnaLib = JNAApiInterface.INSTANCE;
var fp = jnaLib.fopen(fileName.getBytes("GBK"), "w+");
jnaLib.fputs(fileContent, fp);
jnaLib.fseek(fp, 0, 0);
var lenght = fileContent.getBytes().length;
var buf = new byte[lenght + 1];
jnaLib.fgets(buf, buf.length, fp);
var readContent = new String(buf, 0, lenght);
System.out.println(readContent);
}
}
interface JNAApiInterface extends Library {
JNAApiInterface INSTANCE = (JNAApiInterface) Native.loadLibrary(("c"), JNAApiInterface.class);
Pointer fopen(byte[] filename, String mode);
Pointer fputs(String str, Pointer fp);
Pointer fgets(byte[] str, int n, Pointer fp);
int fseek(Pointer fp, long offset, int origin);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment