有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

使用java代码对文本进行编码

我的代码使用servlet语言逐行读取文本,并在字符串缓冲区中每5000个单词填充字符串缓冲区,然后在jsp页面中显示内容,我将标题显示文本放入utf-8。问题是,当utf-8编码的文本以未知字符读取代码时,我希望我的代码读取utf-8中的文本和文本以utf-8编码向用户显示 这是我阅读课文的代码

 try{
   File file = new File(p);         
   l = (int) file.length(); 
   String s = null,strr=null;
   String g = null,m=null;
   int i = 0;
   Scanner input = new Scanner(file); 
   s1 = new StringBuffer();
   s2 = new StringBuffer();
   while (input.hasNextLine()) {
     g = input.nextLine();
     String[] d = g.split(" ");
     int h = d.length;
     i = i + h;
     if (i > 5000) {
       break;
     }
     s1.append(g).append(System.getProperty("line.separator"));
   }
   if(i > 5000) {
     s2.append(g).append(System.getProperty("line.separator"));
     while( input.hasNextLine()) {
     s = input.nextLine(); 
     String[] d = s.split(" ");
     int h = d.length;
     i=0;
     i=i+h;
     if (i > 5000) {
       break;
     }
     s2.append(s).append(System.getProperty("line.separator"));}
     if (input.hasNextLine()) {
       s3.append(s).append(System.getProperty("line.separator"));
       while(input.hasNextLine()) {
         strr = input.nextLine(); 
         s3.append(strr).append(System.getProperty("line.separator"));
       }
     }
   }
 input.close(); 
 } catch (Exception e) {
   e.getMessage();
 }

共 (1) 个答案

  1. # 1 楼答案

    检查您正在使用的方法的javadocs,Scanner(File)构造函数让您知道:

    Bytes from the file are converted into characters using the underlying platform's default charset.

    相反,您可以调用Scanner(File, String)构造函数来显式指定文件编码:

    Scanner input = new Scanner(file, "UTF-8");