用户登录
用户注册

分享至

使用流编写器将特定字节写入文本文件

  • 作者: 大姐有钱就他娘的甩了你
  • 来源: 51数据库
  • 2023-02-13

问题描述

好吧,我正在尝试将一些值和字符串写入文本文件.
但是这个文本文件必须包含 2 个字节

Well I'm trying to write some values and strings to a text file.
but this text file must contain 2 bytes

在完成向文本文件写入其他值后,这些是我想插入到文本文件中的 2 个字节:

These are the 2 bytes I want to insert to my text file after finishing writing the other values to it:

我试过这个方法,但我不知道如何通过它写字节

I tried this method but I have no idea how to write bytes through it

using (StreamWriter sw = new StreamWriter(outputFilePath, false, Encoding.UTF8))

我不知道在把我想要的字符串放在上面后如何将它们写入文本文件.

I have no idea about how to write them to the text file after putting the strings I want on it.

推荐答案

如果我没记错的话.您想将字符串写入文件,然后向其中写入字节吗?

If I recall correctly from your question. You want to write strings to a file and then write bytes to it?

这个例子会为你做到这一点:

This example will do that for you:

using (FileStream fsStream = new FileStream("Bytes.data", FileMode.Create))
using (BinaryWriter writer = new BinaryWriter(fsStream, Encoding.UTF8))
{
    // Writing the strings.
    writer.Write("The");
    writer.Write(" strings");
    writer.Write(" I");
    writer.Write(" want");
    writer.Write(".");

    // Writing your bytes afterwards.
    writer.Write(new byte[]
                 {
                     0xff,
                     0xfe
                 });
}

使用十六进制编辑器打开Bytes.data"文件时,您应该看到以下字节:

When opening the "Bytes.data" file with a hex editor you should see these bytes:

软件
前端设计
程序设计
Java相关