2013-07-13 49 views
-1

我希望将结果保存在文件中,并使用递归方法重写对象并保存任何内容。 如果我尝试申报的PrintWriter globaly那么它给我的错误“默认构造函数不能处理由隐式超级构造函数抛出的异常类型UnsupportedEncodingException。必须定义一个明确的构造函数” 这里是代码在java中编写文件问题

public void lengthFind() { 
    try { 

     writer = new PrintWriter("Results.txt", "UTF-8"); 
     fileStreamTest obj = new fileStreamTest(); 
     Scanner s = new Scanner(new File(path)); 
     int max = 0; 

     while (s.hasNextFloat()) { 

      int d = (int) s.nextFloat(); 

      // it filters the time stamp 
      if (d <= 5000) { 
       String code = obj.GolombCoding(d, dival); 

       // finding Max length 
       if (code.length() > max) { 
        max = code.length(); 
       } 
      } 

     } 

     // Dividend Limit check or increase the Dividend 
     if (dival == 10) { 
      writer.println("Divident has reached it Limit !"); 
      i++; 
      // update the file name 
      path = "D:/File Compression/Data/low_freq/low_freq/house_1/channel_" 
        + i + ".dat"; 
      dival = 10; 

     } else { 
      dival = dival + 10; 
      writer.print("Dividen:" + dival); 
     } 
     writer.print("Max Length of File " + i + ": " + max); 
     writer.println("Path Of the File : " + path); 

     int counter = 1; 
     // recall the method 
     writer.println("Method Call Counter" + counter); 

     lengthFind(); 

    } catch (IOException e) { 
     writer.close(); 
     System.out.println("There is no more File"); 
     System.exit(0); 

    } 
+0

什么是不确切的?你有没有看过[UnsupportedEncodingException的javadoc](http://docs.oracle.com/javase/7/docs/api/java/io/UnsupportedEncodingException.html)?你叫什么“全球声明”? – fge

+0

通过声明全局我的意思是,我在方法中使printwriter对象不在方法 – Waqas

+0

因此,在一个静态初始化? – fge

回答

1

看那javadoc

抛出:

  1. FileNotFoundException - 如果给定的文件对象不表示现有的可写常规文件,并且无法创建该名称的新常规文件,或者在打开或创建文件时发生其他错误

  2. SecurityException - 如果安全管理器存在,并且checkWrite(file.getPath())拒绝写访问该文件

  3. UnsupportedEncodingException - 如果指定字符集不支持

你需要对付Exception构造函数可能抛出。如果要将PrintWriter声明为static,则需要使用静态初始化块。

static PrintWriter pw ; 
static { 
    try{ 
    pw = new PrintWriter("Results.txt", "UTF-8"); 
    } 
    catch(IOException e){ 
     e.printStackTrace(); 
     throw new RuntimeException(e); 
    } 
}