字符看起来像“?”在阅读上传文件的内容

时间:2011-12-27 12:57:37

标签: java file-upload java-io r.java-file

我有一个上传vcf文件的客户端,我在服务器端获取此文件并读取内容并将其保存到txt文件。但是当我尝试阅读时有一个字符错误,如果有土耳其字符,它看起来像“?”。我的阅读代码在这里:

            FileItemStream item = null;
            ServletFileUpload upload = new ServletFileUpload();
            FileItemIterator iterator = upload.getItemIterator(request);
            String encoding = null;
            while (iterator.hasNext()) {
                item = iterator.next();
                if ("fileUpload".equals(item.getFieldName())) {
                    InputStreamReader isr = new InputStreamReader(item.openStream(), "UTF-8");
                    String str = "";
                    String temp="";
                    BufferedReader br = new BufferedReader(isr);
                    while((temp=br.readLine()) != null){
                        str +=temp; 
                    }
                    br.close();
                    File f = new File("C:/sedat.txt");
                    BufferedWriter buf = new BufferedWriter(new FileWriter(f));
                    buf.write(str);
                    buf.close();
             }

1 个答案:

答案 0 :(得分:1)

BufferedWriter buf = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(f), "UTF-8"));

如果这是生产代码,我建议直接将输出写入文件,而不是先将其累积在字符串中。并且,您可以通过将源读取为InputStream并将其写为OutputStream(并将转换跳转到字符)来避免任何潜在的编码问题。