簡體   English   中英

逐行寫入文件

[英]Writing into file line by line

我正在從文本[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
FileWriter writer = new FileWriter("outputfile.txt"); // use your file extension
String content = "My first line";
writer.write(content+"\n");
writer.flush();
//if you have array of string use for loop 
writer.close();
// you should use exception handing always and import relevant classes

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM