Java 文件写入:字符串到字节
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18942154/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
File Write : String to Bytes
提问by HakunaMatata
I want to write string/Char data as bytes in a file.I want this conversion happen internally in IO.* classes. I do not want to use getBytes() method on string.
我想在文件中将字符串/字符数据作为字节写入。我希望这种转换在 IO.* 类内部发生。我不想在字符串上使用 getBytes() 方法。
I tried following two Programs but both are writing data as Character . And when i open the file in notepad i can read these characters. How can i store my data as bytes ?
我尝试遵循两个程序,但都将数据写入 Character 。当我在记事本中打开文件时,我可以读取这些字符。如何将我的数据存储为字节?
import IO.FileWrite;
import java.io.*;
public class CharToChar {
private final String data;
public CharToChar(String data){
this.data = data;
}
public static void main(String[] args) throws IOException {
final CharToChar charToChar = new CharToChar("I am Manish");
charToChar.write();
}
private void write() throws IOException {
final File file = new File("CharToChar.txt");
final FileWriter fileWriter = new FileWriter(file);
final BufferedWriter bufferdWriter = new BufferedWriter(fileWriter);
bufferdWriter.write(this.data);
bufferdWriter.close();
}
}
import java.io.DataOutputStream;
import java.io.FileOutputStream;
import java.io.IOException;
public class WriteStringAsBytesToFile {
public static void main(String[] args) {
String strFilePath = "WriteStringAsBytes.txt";
try
{
//create FileOutputStream object
FileOutputStream fos = new FileOutputStream(strFilePath);
/*
* To create DataOutputStream object from FileOutputStream use,
* DataOutputStream(OutputStream os) constructor.
*
*/
DataOutputStream dos = new DataOutputStream(fos);
String str = "This string will be written to file as sequence of bytes!";
/*
* To write a string as a sequence of bytes to a file, use
* void writeBytes(String str) method of Java DataOutputStream class.
*
* This method writes string as a sequence of bytes to underlying output
* stream (Each character's high eight bits are discarded first).
*/
dos.writeBytes(str);
/*
* To close DataOutputStream use,
* void close() method.
*
*/
dos.close();
}
catch (IOException e)
{
System.out.println("IOException : " + e);
}
}
}
Note - > JAVA docs says OutputStreamWriter An OutputStreamWriter is a bridge from character streams to byte streams: * Characters written to it are encoded into bytes using a specified.
注意-> JAVA 文档说 OutputStreamWriter 一个 OutputStreamWriter 是从字符流到字节流的桥梁: * 写入它的字符使用指定的编码成字节。
采纳答案by rocketboy
I think you have the wrong notion about writing as bytes/chars. Characters, are just representations of byte data. This representation is decided on the bases of Character Encodingtype. Look at the following code:
我认为您对写为字节/字符有错误的看法。字符,只是字节数据的表示。这种表示是根据字符编码类型决定的。看下面的代码:
OutputStream os = new FileOutputStream(filePath);
os.write("This is byte date".getBytes("UTF-8"));
os.close();
If you open your file after running the above snippet, you'll notice the same string in the file. Your file always has data in bytes. The bytes are read by your text editor and encoded based on its default character encoding, usually UTF-8but not always.
如果在运行上述代码段后打开文件,您会注意到文件中存在相同的字符串。您的文件始终包含以字节为单位的数据。字节由您的文本编辑器读取并根据其默认字符编码进行编码,通常为UTF-8,但并非总是如此。
回答by Srikanth Reddy Lingala
Not sure if any of java IO classes can do this, and I see that you don't want to use getBytes()
, but if you decide to go the getBytes()
way, then you can modify your write()
method in your first example to something like this:
不确定是否有任何 java IO 类可以做到这一点,我看到您不想使用getBytes()
,但是如果您决定顺其自然getBytes()
,那么您可以write()
将第一个示例中的方法修改为如下所示:
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Arrays;
import java.util.Arrays;
public class CharToChar {
private final String data;
public CharToChar(String data){
this.data = data;
}
private void write() throws IOException {
OutputStream fos = new FileOutputStream(new File("CharToChar.txt"));
fos.write(Arrays.toString(this.data.getBytes()).getBytes());
fos.close();
}
public static void main(String[] args) throws IOException {
final CharToChar charToChar = new CharToChar("I am Manish");
charToChar.write();
}
}
回答by Renato
Your requirement seems quite odd, as converting a String to bytes is the job of the toBytes
method which you do not want to use.... but you can serialize any Java Object, including Strings, then save it to a File as follows:
您的要求似乎很奇怪,因为将字符串转换为字节是toBytes
您不想使用的方法的工作......但是您可以序列化任何 Java 对象,包括字符串,然后将其保存到文件中,如下所示:
try ( ObjectOutputStream oos = new ObjectOutputStream(
new FileOutputStream( "CharToChar.txt" ) ) ) {
// write any object to a file
oos.writeObject( "I am Manish" );
// another option, works for Strings and makes the String pretty much un-readable
oos.writeBytes( "hello world" );
} catch ( IOException e ) {
e.printStackTrace();
}