简体   繁体   中英

reading and writing files into java

I have to create a file named Lab13.txt. In the file I have 10 numbers. I import the 10 numbers and have to Multiply all the numbers from Lab13.txt by 10 and save all the new numbers a new file named Lab13_scale.txt. so if the number 10 is in lab13.txt it prints 100 to Lab13_scale.txt. Here is what I have:

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();

    }

}

How do I multiply the numbers by 10 and export it to the new file?

This code is simple as this:

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();
    }

}

I'll give you a different approach. I have wrote this from memory, let me know if you have any errors. I assumed the numbers are one on each line.

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){}
}

If the numbers are separated by spaces, use

file.nextInt();

Full Code:

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

after writer.println("");

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM