简体   繁体   English

读取文件并将其写入Java

[英]reading and writing files into java

I have to create a file named Lab13.txt. 我必须创建一个名为Lab13.txt的文件。 In the file I have 10 numbers. 在文件中,我有10个数字。 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. 我导入了10个数字,必须将Lab13.txt中的所有数字乘以10,然后将所有新数字保存到名为Lab13_scale.txt的新文件中。 so if the number 10 is in lab13.txt it prints 100 to Lab13_scale.txt. 因此,如果数字13位于lab13.txt中,则它将100输出到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? 如何将数字乘以10并将其导出到新文件?

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(""); writer.println("");

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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