我有这个代码,我正在努力,我可以从文件中读取,但我不能保存我的txt文件的答案。另外我如何回忆在相同的数字上做其他操作。我需要一个如何做到这一点的提示
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);
}
}
}
答案 0 :(得分: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();
}
}