读取和写入文件到java

时间:2015-04-17 03:52:12

标签: java

我必须创建一个名为Lab13.txt的文件。在文件中我有10个数字。我导入了10个数字,并且必须将Lab13.txt中的所有数字乘以10,并将所有新数字保存为名为Lab13_scale.txt的新文件。因此,如果数字10在lab13.txt中,它将100打印到Lab13_scale.txt。这是什么 我有:

import java.io.*;

import java.util.Scanner;
public class lab13 {

    public static void main(String[] args) throws IOException{
        File temp = new File("Lab13.txt");
        Scanner file= new Scanner(temp);


        PrintWriter writer = new PrintWriter("Lab13_scale.txt", "UTF-8");
        writer.println("");
        writer.close();

    }

}

如何将数字乘以10并将其导出到新文件?

3 个答案:

答案 0 :(得分:1)

这段代码很简单:

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


public class Lab13 {

    public static void main(String[] args) throws FileNotFoundException {
        Scanner scan = new Scanner(new File("Lab13.txt"));
        PrintWriter print = new PrintWriter(new File("Lab13_scale.txt"));

        while(scan.hasNext()){
            print.write(10 * scan.nextInt()+"\n");
        }
        print.close();
        scan.close();
    }

}

答案 1 :(得分:0)

我会给你一个不同的方法。我是从记忆中写的,如果你有任何错误,请告诉我。我假设每行都有一个数字。

public static void main(String[] args)
{

  String toWrite = "";
  try{
   String line;
   BufferedReader reader = new BufferedReader(new FileReader("Lab13.txt"));
   while((line = reader.readLine())!=null){
       int x = Integer.parseInt(line);
       toWrite += (x*10) + "\n";
   }
   File output = new File("lab13_scale.txt");
   if(!output.exists()) output.createNewFile();
   FileWriter writer = new FileWriter(output.getAbsoluteFile());
   BufferedWriter bWriter= new BufferedWriter(writer);
   bWriter.write(toWrite);
   bWriter.close();
 }catch(Exception e){}
}

答案 2 :(得分:0)

如果数字以空格分隔,请使用

file.nextInt();

完整代码:

int[] nums = new int[10];
for(int i = 0; i < 10; i++){
    nums[i] = file.nextInt();
    nums[i] *= 10;
}
writer.println("");

之后

for(int i = 0; i < 10; i++){
    writer.println(nums[i]);
}