2014-12-05 24 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 2014-12-05 02:15:10

+0

如果您需要提示,請查看[FileWriter](https://docs.oracle.com/javase/7/docs/api/java/io/FileWriter.html) – Baby 2014-12-05 02:16:17

回答

0

您需要使用一個文件寫入器寫入文件和文件讀取器來寫入文件。您還需要導入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(); 
    } 
}