gpt4 book ai didi

java - 逐行写入文件

转载 作者:太空宇宙 更新时间:2023-11-04 15:07:13 25 4
gpt4 key购买 nike

我正在从文本 [utf8 格式] 文件中读取数据并将其存储在字符串中,然后将该字符串转换为十六进制格式并将该十六进制字符串保存到另一个文件中,但我想逐行保存此转换后的十六进制字符串。如何做到这一点?

        String sCurrentLine;
br = new BufferedReader(new FileReader("demmo123.txt"));
while ((sCurrentLine = br.readLine()) != null) {
sb1.append(sCurrentLine);
}
String ss = sb1.toString();
Scanner sc = new Scanner(ss);
String helloWorldHex = toHexString(ss.getBytes());
file = new File("demmo.txt");
fop = new FileOutputStream(file);
if (!file.exists()) {
file.createNewFile();
}
byte[] contentInBytes = helloWorldHex.getBytes();
fop.write(helloWorldHex.getBytes());
fop.write(contentInBytes);
fop.flush();
fop.close();
fop.write(helloWorldHex.getBytes());

最佳答案

对于输入数据:

test string 1
test string 2
test string 3
test string 4


import java.io.File;
import java.io.FileNotFoundException;
import java.io.PrintWriter;
import java.util.Scanner;

public class Example {
public static void main(String[] args) {

try {
File input = new File("C:\\temp\\input.txt");
File output = new File("C:\\temp\\output.txt");

Scanner scanner = new Scanner(input);
PrintWriter printer = new PrintWriter(output);
while(scanner.hasNextLine()) {
String string = scanner.nextLine();
StringBuilder stringBuilder = new StringBuilder(200);
for(char ch: string.toCharArray()) {
if(stringBuilder.length() > 0) stringBuilder.append(' ');
stringBuilder.append(String.format("%04x", (int)ch));
}
printer.write(stringBuilder.toString());
printer.write("\r\n");
}
printer.flush();
printer.close();
}
catch(FileNotFoundException e) {
System.err.println("File not found.");
}
}

}

它给出:

0074 0065 0073 0074 0020 0073 0074 0072 0069 006e 0067 0020 0031
0074 0065 0073 0074 0020 0073 0074 0072 0069 006e 0067 0020 0032
0074 0065 0073 0074 0020 0073 0074 0072 0069 006e 0067 0020 0033
0074 0065 0073 0074 0020 0073 0074 0072 0069 006e 0067 0020 0034

关于java - 逐行写入文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21829901/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com