用java代码对文本进行编码

用java代码对文本进行编码,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=

我的代码使用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();
 }

检查您正在使用的方法的javadocs-构造函数让您知道:

使用基础平台的默认字符集将文件中的字节转换为字符

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

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

你能试着用大写字母和标点符号吗?理解这篇没有结构的文章很复杂。提前谢谢。把文章分成段落可能是个好主意too@Andrzej:是的!:)我的大脑拒绝解析问题文本,产生了一个可怕的异常。我使用usebean标记Thanke you在另一个jsp页面中显示文本,我尝试了你的答案,但没有结果shown@user这听起来不错,因为你没有任何
println
语句。或者你是说你有理由相信指定字符集意味着文件被认为是空的??我使用usebean标记在jsp页面中显示文本。文件不是空的,但当我使用你的答案时,文本不会显示