2014-12-05 5 views
-3

나는이 파일을 읽을 수 있습니다. 그러나 txt 파일에 대한 답을 저장할 수 없습니다. 또한 다른 작업을 수행 할 때 어떻게 기억합니까? 같은 번호 .i 어떻게해야하는지에 대한 조언이 필요합니다.어떻게 파일을 읽고 쓸 수 있습니까?/O

package x; 

import java.io.File; 
import java.io.FileNotFoundException; 
import java.util.Scanner; 



public class x { 

    public static void main(String args[]) throws FileNotFoundException { 

     //creating File instance to reference text file in Java 
     File text = new File("C:\\Users\\user\\Desktop\\testScanner.txt"); 

     //Creating Scanner instnace to read File in Java 
     Scanner scnr = new Scanner(text); 

     //Reading each line of file using Scanner class 
     int lineNumber = 1; 
     while(scnr.hasNextLine()){ 
      String line = scnr.nextLine(); 
      int foo = Integer.parseInt(line); 

      System.out.println("==================================="); 
      System.out.println("line " + lineNumber + " :" + line); 
      foo=100*foo; 
      lineNumber++; 
      System.out.println(" foo=100*foo " + lineNumber + " :" + foo); 
     }  

    } 

} 
+1

지금까지 시도한 것은 무엇입니까? 더 나은 (그리고 더 빠른) 답변을 얻으려면 [this] (http://stackoverflow.com/help/on-topic)을 읽어보십시오. – FlyingPiMonster

+0

팁이 필요하면 [FileWriter] (https://docs.oracle.com/javase/7/docs/api/java/io/FileWriter.html)를 살펴보십시오. – Baby

답변

0

당신은 파일을 작성하는 파일 및 파일 리더를 작성하는 filewriter를 사용해야합니다. 당신은 또한 java.io를 가져올 필요가있다. 여기에 예제 코드가 있습니다 :

import java.io.*; 

public class FileRead{ 

    public static void main(String args[])throws IOException{ 

     File file = new File("Hello1.txt"); 
     // creates the file 
     file.createNewFile(); 
     // creates a FileWriter Object 
     FileWriter writer = new FileWriter(file); 
     // Writes the content to the file 
     writer.write("This\n is\n an\n example\n"); 
     writer.flush(); 
     writer.close(); 

     //Creates a FileReader Object 
     FileReader fr = new FileReader(file); 
     char [] a = new char[50]; 
     fr.read(a); // reads the content to the array 
     for(char c : a) 
      System.out.print(c); //prints the characters one by one 
     fr.close(); 
    } 
} 
관련 문제