Swift-将字节流写入文件 [英] Swift - writing a byte stream to file

查看:903
本文介绍了Swift-将字节流写入文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个数百字节的字符串和一些Int32值.我想将这些文字逐字写入文件中.

I have a string of several hundred bytes and some Int32 values. I want to write these to a file, verbatim.

我尝试了许多建议的解决方案,但没有一个对我有用.文件中出现多余的括号,空格或逗号.

I have tried many suggested solutions and none have worked for me. I get extraneous brackets or spaces or commas in the file.

有人可以提出一个简单,可靠的解决方案吗?

Can anyone suggest a simple, reliable solution?

我认为我的问题很明确,但是在阅读评论后,我已经简化了.

I thought my question was very clear, but after reading the comments, I have simplified it.

如何将"12345"写入和/或附加到文件中,以使该文件包含以下十六进制值:3132333435?

How do I write and/or append "12345" to a file so that the file contains the following Hex values: 3132333435 ?

通过写入NSData字符串,我可以获得的最佳结果是< 3132333435>.

The best result I can obtain is <3132333435>, by writing an NSData string.

我可以使用以下链接获得所需的结果:

I can get the desired result using this link: Does swift have a protocol for writing a stream of bytes?, but I cannot append data to the file I have created.

推荐答案

我建议使用NSFileHandle.

I would suggest using NSFileHandle.

我这样测试.我从文件〜/Desktop/test.txt 开始,其中包含单词"testing".然后,我运行以下代码:

I tested like this. I started with a file ~/Desktop/test.txt containing the word "testing". I then ran this code:

    let s = "12345"
    let d = s.dataUsingEncoding(NSASCIIStringEncoding)!
    let path = ("~/Desktop/test.txt" as NSString).stringByExpandingTildeInPath
    if let fh = NSFileHandle(forWritingAtPath: path) {
        fh.seekToEndOfFile()
        fh.writeData(d)
        fh.closeFile()
    }

结果是该文件现在包含

testing12345

十六进制转储显示基本字节为:

A hex dump revealed that the underlying bytes were:

74 65 73 74 69 6E 67 31 32 33 34 35

我相信这就是您想要实现的目标.

I believe that's what you said you wanted to achieve.

另外,进一步的评价:

我可以获得的最佳结果是<3132333435>

在这里听起来好像问题仅在于您不知道如何读取控制台输出. <>不在文件中;它们只是数据的控制台表示的一部分.最好使用BBEdit/TextWrangler或专用的十六进制转储程序来查看文件的实际字节.

It sounds here as if the problem is merely that you don't know how to read the console output. The < and > are not really in the file; they are just part of the console representation of data. It would be better to use BBEdit / TextWrangler or a dedicated hex dumper to see the actual byte of the file.

这篇关于Swift-将字节流写入文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆