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

我怕爱的太早我们不能终老 提交于 2019-11-28 14:06:21

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());
        } 
    }
}

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 
  }

}

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

ekta
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);

     }  
} 

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!