繁体   English   中英

Java如何将文件中的字符串作为字节写入并取回字符串

[英]Java How to write a string in file as bytes and get string back

我需要在文件中将字符串写为UTF-8中的字节,然后从文件中获取这些字节,然后将其转换回字符串,并且出于意愿而获得相同的字符串。 听起来可能很简单,但是存在隐藏的问题,例如文件中的符号不​​正确。 我的意思是,在文件中追加后,它必须包含类似以下内容的内容:

00000008 d0bad0bb d18ed187 00000010等...

但是它包含如下内容:

mystring ---很大的空间---(以及此处未显示的符号)

那么,我已经做了什么? 我已经尝试过这种方式:

在代码阅读之前:我将字符串保留在HashMap <String,String>中,这就是为什么我的代码包含get(...)等的原因。

try {
        FileOutputStream oStream = new FileOutputStream("filename.txt");
        Set<String> keySet = storage.keySet();
        ByteBuffer buffer = ByteBuffer.allocate(1024);
        for (String key : keySet) {
            byte[] keyInByte = key.getBytes("UTF-8");
            byte[] valueInByte = storage.get(key).getBytes("UTF-8");
            oStream.write(buffer.putInt(0, valueInByte.length).array());
            oStream.write(keyInByte);

            oStream.write((buffer.putInt(0, valueInByte.length).array()));
            oStream.write(valueInByte);
        }
    } catch (Exception e) {
        System.err.println("permission denied");
    }

我也尝试过使用PrintWriter,FileWriter等...但是它不能满足我的需求。 例如,其中一些需要toString()方法,但是在toString()之后,我将失去使用字节的能力。

注意,我已经尝试将记事本更改为UTF-8编码,但是没有任何结果。

如果要使用属性,可以执行此操作。

new Properties(map).save(new FileOutputStream("filename.proeprties"));

加载属性

Properties prop = new Properties();
prop.load(new FileInputStream("filename.properties"));
map.putAll(prop);

要保存复制的数据,可以将“属性”用作地图。

key1=value1
key2=value2

注意:键不能包含=或换行符。


这就是我将以二进制格式执行的方式

DataOutputStream dos = new BufferedOutputStream(new FileOutputStream("filename.dat")));
dos.writeInt(map.size());
for (Map.Entry<String, String> entry : map.entrySet()) {
    dos.writeUTF(entry.getKey());
    dos.writeUTF(entry.getValue());
}
dos.close();

这就是我使用UTF-8以文本形式编写的方式

PrintWriter pw = new PrintWriter(new OutputStreamWriter(new FileOuputStream("filename.txt") "UTF-8"));
pw.println(map.size());
for (Map.Entry<String, String> entry : map.entrySet()) {
     pw.println(encode(entry.getKey()));
     pw.println(encode(entry.getValue()));
}
pw.close();


public static String encode(String s) {
    // if you can assume no new lines, don't do anything.
    return s.replaceAll("\\\\", "\\\\\\\\").replaceAll("\n", "\\\\n");
}

这会产生像

key1
value1
key2
value2

您可以很容易地进行编辑。 如果您假设键没有=:或制表符,则可以像属性文件一样使用一行

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM