茫茫網海中的冷日
         
茫茫網海中的冷日
發生過的事,不可能遺忘,只是想不起來而已!
 恭喜您是本站第 1670797 位訪客!  登入  | 註冊
主選單

Google 自訂搜尋

Goole 廣告

隨機相片
IMG_60D_00036.jpg

授權條款

使用者登入
使用者名稱:

密碼:


忘了密碼?

現在就註冊!

爪哇咖啡屋 : [轉貼]How to write a UTF-8 file with Java?

發表者 討論內容
冷日
(冷日)
Webmaster
  • 註冊日: 2008/2/19
  • 來自:
  • 發表數: 15771
[轉貼]How to write a UTF-8 file with Java?
How to write a UTF-8 file with Java?

I have some current code and the problem is its creating a 1252 codepage file, i want to force it to create a UTF-8 file
Can anyone help me with this code, as i say it currently works... but i need to force the save on utf.. can i pass a parameter or something??
this is what i have, any help really appreciated
var out = new java.io.FileWriter( new java.io.File( path )),
        text = new java.lang.String( src || "" );
    out.write( text, 0, text.length() );
    out.flush();
    out.close();




Instead of using FileWriter, create a FileOutputStream. You can then wrap this in an OutputStreamWriter, which allows you to pass an encoding in the constructor. Then you can write your data to that inside a try-with-resources Statement:
try (OutputStreamWriter writer =
             new OutputStreamWriter(new FileOutputStream(PROPERTIES_FILE), StandardCharsets.UTF_8))
    // do stuff
}




Try this
Writer out = new BufferedWriter(new OutputStreamWriter(
    new FileOutputStream("outfilename"), "UTF-8"));
try {
    out.write(aString);
} finally {
    out.close();
}




Try using FileUtils.write from Apache Commons.
You should be able to do something like:
File f = new File("output.txt");
FileUtils.writeStringToFile(f, document.outerHtml(), "UTF-8");

This will create the file if it does not exist.



All of the answers given here wont work since java's UTF-8 writing is bugged.
http://tripoverit.blogspot.com/2007/04/javas-utf-8-and-unicode-writing-is.html



Since Java 7 you can do the same with Files.newBufferedWriter a little more succinctly:
Path logFile = Paths.get("/tmp/example.txt");
try (BufferedWriter writer = Files.newBufferedWriter(logFile, StandardCharsets.UTF_8)) {
    writer.write("Hello World!");
    // ...
}




var out = new java.io.PrintWriter(new java.io.File(path), "UTF-8");
text = new java.lang.String( src || "" );
out.print(text);
out.flush();
out.close();




The Java 7 Files utility type is useful for working with files:
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.io.IOException;
import java.util.*;

public class WriteReadUtf8 {
  public static void main(String[] args) throws IOException {
    List<String> lines = Arrays.asList("These", "are", "lines");

    Path textFile = Paths.get("foo.txt");
    Files.write(textFile, lines, StandardCharsets.UTF_8);

    List<String> read = Files.readAllLines(textFile, StandardCharsets.UTF_8);

    System.out.println(lines.equals(read));
  }
}

The Java 8 version allows you to omit the Charset argument - the methods default to UTF-8.



we can write the UTF-8 encoded file with java using use PrintWriter to write UTF-8 encoded xml
Or Click here
PrintWriter out1 = new PrintWriter(new File("C:\\abc.xml"), "UTF-8");




Below sample code can read file line by line and write new file in UTF-8 format. Also, i am explicitly specifying Cp1252 encoding.
    public static void main(String args[]) throws IOException {
    BufferedReader br = new BufferedReader(new InputStreamReader(
            new FileInputStream("c:\\filenonUTF.txt"),
            "Cp1252"));
    String line;
    Writer out = new BufferedWriter(
            new OutputStreamWriter(new FileOutputStream(
                    "c:\\fileUTF.txt"), "UTF-8"));
    try {
        while ((line = br.readLine()) != null) {
            out.write(line);
            out.write("\n");
        }
    } finally {
        br.close();
        out.close();
    }
}


原文出處:How to write a UTF-8 file with Java? - Stack Overflow
冷日
(冷日)
Webmaster
  • 註冊日: 2008/2/19
  • 來自:
  • 發表數: 15771
[轉貼]Java FileWriter 類

Java FileWriter類

這個類繼承自的OutputStreamWriter類。這個類是用於寫入字符流。

這個類有幾個構造函數來創建所需的對象。

下面的語法創建一個給定的文件對象文件字符寫對象。



FileWriter(File file)

下面的語法創建一個給定的文件對象文件字符寫對象。



FileWriter(File file, boolean append)

以下語法創建了一個文件描述符關聯的文件字符寫的對象。



FileWriter(FileDescriptor fd)

下面的語法創建給定文件名的文件字符寫對象。



FileWriter(String fileName)

下面的語法創建一個文件字符寫對象給出一個布爾值,指示是否附加寫入數據的文件名。



FileWriter(String fileName, boolean append)

一旦有文件字符寫對象,再有就是使用helper方法的列表,它可以用來操作文件。

SN 方法及描述
1
public void write(int c) throws IOException
寫入單個字符。
2 public void write(char [] c, int offset, int len)
寫入字符數組的偏離,len長度開始的部分。
3 public void write(String s, int offset, int len)
寫一個字符串的一部分從偏移和len長度開始。

例子:


下面的例子是用來演示:



import java.io.*;
public class FileRead{
public static void main(String args[])throws IOException{
File file = new File("Hello1.txt");
// creates the file
file
.createNewFile();
// creates a FileWriter Object
FileWriter writer = new FileWriter(file);
// Writes the content to the file
writer
.write("This
is
an
example
"
);
writer
.flush();
writer
.close();
//Creates a FileReader Object
FileReader fr = new FileReader(file);
char [] a = new char[50];
fr
.read(a); // reads the content to the array
for(char c : a)
System.out.print(c); //prints the characters one by one
fr
.close();
}
}

這將產生以下結果:



This
is
an
example



原文出處:Java FileWriter類 - Java基礎教程
冷日
(冷日)
Webmaster
  • 註冊日: 2008/2/19
  • 來自:
  • 發表數: 15771
[轉貼]Appending to file in utf8
Appending to file in utf8

For a project I need to append to a textfile using UTF-8 encoding. During my research I found two possibilities:
BufferedWriter out = new BufferedWriter(
    new OutputStreamWriter(new FileOutputStream("file.txt), "UTF-8")
)

This will write to my file in UTF-8, but it will overwrite it, rather than append to it if it already exist.
Then I found the code to apend to an existing file with a parameter in the FileWriter, but this will not use UTF-8 explicitely, rather than use the default system character set:
BufferedWriter out = new BufferedWriter(new FileWriter("myfile.txt", true))

I now need the possibility to define BOTH the encoding as well as appending to a file. Just rely on the system encoding or change this is not an option.



You forgot to add the true paramter to the FileOutputStream constructor:
BufferedWriter out = new BufferedWriter(
    new OutputStreamWriter(
        new FileOutputStream("file.txt", true), // true to append
        StandardCharsets.UTF_8                  // Set encoding
    )
);




try {
    BufferedWriter out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream("myFile.txt", true), "UTF-8"));
    out.write("Hello World");
    out.close();
} catch (IOException e) {
    e.printStackTrace();
}


原文出處java - Appending to file in utf8 - Stack Overflow
前一個主題 | 下一個主題 | 頁首 | | |



Powered by XOOPS 2.0 © 2001-2008 The XOOPS Project|