unreported exception java.io.FileNotFoundException; must be caught or declared to be thrown

前端 未结 5 1554
后悔当初
后悔当初 2020-12-11 22:58

I am creating a class -- just a class, no main() and I am receiving the error of \"unreported exception java.io.FileNotFoundException; must be caught or declared to be throw

相关标签:
5条回答
  • 2020-12-11 23:28

    All functional code needs to go into methods - I don't see a method in your code - that's the illegal start of type problem. The other compile errors should become clearer once you get the basics down.

    public class Foo {
    
      public void doSomething() {
        //code here 
      }
    
    }
    
    0 讨论(0)
  • 2020-12-11 23:29

    Move this code to some method or at least to a static initializer block.

    0 讨论(0)
  • 2020-12-11 23:29
    import java.io.*;
    import java.util.*; 
    
    public class SortNames {
    
    private String[] strings = new String[10];  
    
    private int counter;
    
    public SortNames() {
    
    ArrayList<String> names = new ArrayList<String>();
    Scanner scan = null;
    File f = null;
    
    try{
     f = new File("names.txt");
     scan = new Scanner(f);
    
      while(scan.hasNext()) names.add(scan.next());
    }
      finally{scan.close();}
    
    Collections.sort(names);
    
      for(String s:names) System.out.println(s);
    
         }  
    } 
    
    0 讨论(0)
  • 2020-12-11 23:31

    You need to put the file processing statements inside a method:

    import java.io.FileOutputStream;
    import java.io.FileNotFoundException;
    
    public class UseLoggingOutputStream {
        public void myMethod() {
            String file = "c:\\system.txt";
            try {
                FileOutputStream outStr = new FileOutputStream(file, true);
            } catch(FileNotFoundException fnfe) { 
                System.out.println(fnfe.getMessage());
            } 
        }
    }
    
    0 讨论(0)
  • 2020-12-11 23:31

    Sorry if this isn't helpful to you, but I was able to solve this exact issue by adding " throws FileNotFoundException " to my method call that contained the FileWriter. I know this may not be helpful since you aren't using methods, but then again, maybe it is.

    0 讨论(0)
提交回复
热议问题