2

I have a simple java program that reads a line from file and writes it to another file.

My source file has words like: it's but the destination file is having words like it�s.

I am using BufferedReader br = new BufferedReader(new FileReader(inputFile)); to read the source file and PrintWriter writer = new PrintWriter(resultFile, "UTF-8"); to write the destination file.

How to get the actual character in my destination file too?

user3392464
  • 141
  • 1
  • 9
  • 5
    You are probably using the wrong charset to read the file; given that you don't specify one, it is the JVM's default which will be used (which is implementation- and platform-dependent). – fge Mar 20 '14 at 16:17
  • then how to deal with it to get the correct copying? – user3392464 Mar 20 '14 at 16:19
  • Use the appropriate `FileReader` constructor as mentioned in the answer – fge Mar 20 '14 at 16:25
  • possible duplicate of [Java FileReader encoding issue](http://stackoverflow.com/questions/696626/java-filereader-encoding-issue) – Steve Benett Mar 20 '14 at 16:25

2 Answers2

2

You need to specify a CharacterSet when creating the BufferedReader, otherwise the platform default encoding is used:

BufferedReader br = new BufferedReader(new FileReader(inputFile),"UTF-8");
Steven Pessall
  • 983
  • 5
  • 15
  • 1
    Using Java 7 this can be written `Files.newBufferedReader(Paths.get(inputFile), StandardCharsets.UTF_8)`. – fge Mar 20 '14 at 16:25
  • I tried as mentioned in answer, but it is giving error `Incompatible type: string can not be converted into int` – user3392464 Mar 20 '14 at 16:38
  • At what line does that exception occur? Could you add more of your code (i.e. the method, which performs the reading and writing) in your question? – Steven Pessall Mar 24 '14 at 06:58
0

I know this question is a bit old, but I thought I'd put down my answer anyway.

You can use java.nio.file.Files to read the file and java.io.RandomAccessFile to write to your destination file. For example:

public void copyContentsOfFile(File source, File destination){
    Path p = Paths.get(source.toURI());
    try {
        byte[] bytes = Files.readAllBytes(p);
        RandomAccessFile raf = new RandomAccessFile(destination, "rw");
        raf.writeBytes(new String(bytes));
        raf.close();
    } catch (IOException e) {
        e.printStackTrace();
    }
}
JD9999
  • 394
  • 1
  • 7
  • 18