2014-03-06 1 views
0
import java.io.File; 
import java.io.FileReader; 
import java.util.Scanner; 

public class lab4 { 

    public static void main(String[] args){ 

     /* 
     * Input is the name of the file and location typed by the user 
     * file is used as a new scanner of the file to later go into the FileReader 
     */ 

     String input; 
     Scanner file; 

     System.out.println("Please type the name of the file you wish to read into the program"); 

     // scanner to acquire input 
     Scanner scanner = new Scanner(System.in); 

     input = scanner.nextLine(); 

     System.out.println("the file input was " + input); 

     // tries to attach the specified file "input" to a new scanner "file" to later read into FileReader 
     try{ 
      file = new Scanner(new File(input)); 
     } 
     catch(Exception e){ 
      System.out.println("The requested file could not be found"); 
     } 

     FileReader(File file){ 
      while(file.hasNext()){ 
       String s = file.next(); 

      } 
     } 
    } 

} 

로 문제를 파악하지 못할, 나는 예를 보면서 무엇을 메신저를 잘해야하고,이 난을 FileReader에 오류를 명중 각각의 새로운 추가 후 컴파일 곳에있어 프로그래밍에 몇 가지 긴 문제 이후의 FileReader

java: ')' expected 
java: illegal start of expression 
java: ';' expected 
java: class, interface, or enum expected 

오류가 FileReader 위치를 가리키고 있으므로 분명히 잘못 사용하고 있습니다. 필요하지 않습니다. 내가 본 예제는 public void FileReader (File "fileName")와 같은 메서드를 만드는 것입니다. public static void main (String [] args)에 내 코드의 전체를 넣으라고했습니다.

나는 youtube를 봤고 API 및 주사위 없음. 더 나은 코딩 연습 지역 변수 input와 main() 메소드의 file 외부를 정의하는 아마

+1

:

에 관계없이, 다음은 샘플입니까? 메서드 내에서 메서드처럼 보이기 때문에 (사용자가 할 수는 없습니다.) 원하는대로 메서드를 만들거나 FileReader 인스턴스를 만들 수 있습니다. – John3136

답변

1

... 이런

public static String input; ...

public static Scanner file;이 ...

코드는 사용하기 전에 이러한 로컬 변수를 초기화했기 때문에 여전히 작동합니다. 컴파일러가 해석하기 까다로울 수 있기 때문에 이것이 처음에는 문제가 될 수 있다고 생각했습니다. 그럼에도 불구하고 main()의 정적 컨텍스트로 작업하기 위해 static 수정자를 사용하는 한 이러한 변수를 main 외부에서 선언하는 것은 상처를주지 않습니다.

Java가 로컬 변수를 자동으로 초기화하지 않습니다. 메소드에서 사용되기 전에 초기화되지 않으면 오류가 발생할 수 있습니다.

또한 FileReader는 클래스이며 메서드와 같은 방식으로 사용할 수 없습니다. 먼저 FileReader 개체를 인스턴스화해야합니다. 그런 다음 개체 참조에 대한 메서드를 호출하고 참조를 통해 FileReader 개체의 멤버 필드 상태를 변경할 수 있습니다.

Java 7 API에 따르면 3 가지 방법으로 java.io.FileReader 객체를 인스턴스화 할 수 있습니다. 편도는 File 객체를 사용하고, 다른 객체는 String 객체를 사용하고 다른 객체는 익숙하지 않은 다른 종류의 객체를 사용합니다. 또한, http://docs.oracle.com/javase/7/docs/api/java/io/File.html

이 남자를 체크 아웃 : 당신이 약간의 시간이있을 때

FileReader fR = new FileReader("myfile.csv"); 

또는

FileReader fR2 = new FileReader(new File("myOtherFile.txt")); 

이 문서를 읽기 :

그래서 예를 들어, 당신은과 같이 FileReader와의 인스턴스 수 파일 읽기시 코드 : http://www.mkyong.com/java/how-to-read-file-from-java-bufferedreader-example/

마지막으로 파일을 읽도록 프로그램을 편집했습니다 :

import java.io.File; 
    import java.io.FileReader; 
    import java.util.Scanner; 
    import java.io.*; 

    public class lab4 { 

static BufferedReader br = null; 


public static void main(String[] args){ 
String s = null; 

    /* 
    * Input is the name of the file and location typed by the user 
    * file is used as a new scanner of the file to later go into the FileReader 
    */ 

    String input; 
    Scanner file; 

    System.out.println("Please type the name of the file you wish to read into the program"); 

    // scanner to acquire input 
    Scanner scanner = new Scanner(System.in); 

    input = scanner.nextLine(); 

    System.out.println("the file input was " + input); 

    // tries to attach the specified file "input" to a new scanner "file" to later read into FileReader 
    try{ 
     // wrap the FileReader object instantiated from the input variable in a 
     // BufferedReader object 
    br = new BufferedReader(new FileReader(input)); 

    // read each line to the console in this while loop that runs as long as it does not equal null 
    while((s = br.readLine()) != null){ 
    System.out.println(s); 
    } 
    } 
    catch(Exception e){ 
     System.out.println("The requested file could not be found"); 
    } 


} 

} 

해피 코딩!

이 기능이 작동하는지 알려주세요.

1

이와 같은 작업을 수행하기 전에 Java의 기본 사항을 따라야합니다.당신은`FileReader` 블록이하고있는 것을 어떻게 생각하십니까

try 
    { 
     File file = new File("input-file.txt"); 
     FileReader fileReader = new FileReader(file); 
     BufferedReader bufferedReader = new BufferedReader(fileReader); 
     String line = null; 
     while ((line = bufferedReader.readLine()) != null) 
     { 
      // do stuff with the line that was read 
     } 
    } 
    catch (FileNotFoundException e) 
    { 
     e.printStackTrace(); 
    } 
    catch (IOException e) 
    { 
     e.printStackTrace(); 
    } 
+0

네, 제 2 프로그래밍 클래스는 FileReader : S에 소개되었습니다. 여전히 기본에 충실^_^도움을 주셔서 감사합니다! 메신저 기본 문자열 내부 코드를 스트립에 대해 생각하고 YouTube 튜토리얼, 그냥 위선적 인 말투가 약간의 예제를 볼 것입니다 friday와 너무 많은 점을 느슨하게 다른 방식으로 일을하지 않습니다. – user2884009

+0

나는 당신을 낙담시킬 뜻이 아니 었습니다. 그것은 제 2의 반열에 꽤 좋았습니다. 당신은 잠시 후에 그것을 얻을 것이다. 'FileReader'는 (당신이 작성한 것처럼) 당신이 호출하는 메소드가 아니라 "인스턴스화"하는 클래스입니다. 이것은 정말로 유일한 오해입니다. 행운을 빌어 요 동료 코더! –