-2

运行它时,我在控制台中收到此错误消息。我哪里出错了?“显示 C:/Users/Nimit/Desktop/n.txt 时出错”

import java.io.IOException;
import javax.swing.*;
public class exmpleText
{
    public static void main(String[] args)
    {
        String url = "C:/Users/Nimit/Desktop/n.txt";
        try
        {
            JFrame frame=new JFrame("Hi");
            JEditorPane Pane = new JEditorPane(url);
            Pane.setEditable(false);
            frame.add(new JScrollPane(Pane));
        } 
        catch(IOException ioe) 
        {
            System.err.println("Error displaying " + url);
        }
    }
}
4

4 回答 4

5

你的第一个错误是这条线。

    System.err.println("Error displaying " + url);

错误不在于它在做什么,而在于它没有做什么。还应该做的是(至少)打印出异常消息,最好是堆栈跟踪。


现在您已经看到/向我们展示了堆栈跟踪,很清楚潜在的错误是什么。该字符串"C:/Users/Nimit/Desktop/n.txt"不是有效的 URL。有效的文件 URL 以"file:"方案开头。

带有 Windows 驱动器号的文件 URL 写成"file:///C:/Users/Nimit/Desktop/n.txt".

参考:http: //blogs.msdn.com/b/ie/archive/2006/12/06/file-uris-in-windows.aspx

或者,您可以使用 将路径名转换为 URL new File("some path").toURL()

于 2012-06-08T06:23:03.990 回答
3

您应该显示堆栈跟踪以了解实际情况,使用ioe.printStackTrace()

import java.io.IOException;
import javax.swing.*;

public class ExempleText {

    public static void main(String[] args) {
        String url = "C:/Users/Nimit/Desktop/n.txt";
        try {
            JFrame frame=new JFrame("Hi");
            JEditorPane Pane = new JEditorPane(url);
            Pane.setEditable(false);
            frame.add(new JScrollPane(Pane));
        } catch(IOException ioe) {
            System.err.println("Error displaying " + url);
            ioe.printStackTrace();
        }
    }
}
于 2012-06-08T06:33:50.873 回答
0

在创建 JFrame 对象后添加此代码

 try{

editorPane.setContentType("text/html");

Reader fileRead=new FileReader(name); // name is the file you want to read

editorPane.read(fileRead,null);

} catch(Exception e) { 

e.printStackTrace();
}
于 2012-06-08T06:49:47.957 回答
0

更正的代码

import java.io.*;
import javax.swing.*;
import java.net.*;

public class exmpleText
{

  public static void main(String[] args)
  {
    String url = "C:\\Users\\welcome\\z.txt";
    File f = new File(url);

    try
    {
      URL x = f.toURL();
      System.out.println(x);         

      JFrame frame=new JFrame("Hi");

      JEditorPane Pane = new JEditorPane(x);
      Pane.setEditable(false);

      frame.add(new JScrollPane(Pane));
      frame.setVisible(true);
    } 
    catch(Exception ioe) 
    {
      System.out.println(ioe);
      System.err.println("Error displaying " + url);
    }
  }
}
于 2012-06-08T06:43:10.363 回答