简体   繁体   English

如何从java中的文件中读取字符串和数字?

[英]How to read strings and numbers from file in java?

如何从文件中读取字符串或数字,它们之间有一个空格。

You can just write a class which will read a file and remove the spaces.您可以编写一个类来读取文件并删除空格。

package com.example.removespaces

import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;


public class RemoveSpacesInFileEx {

    public static void main(String[] args) throws FileNotFoundException, IOException {

        FileReader fr = new FileReader("input.txt"); 
        BufferedReader br = new BufferedReader(fr); 
        FileWriter fw = new FileWriter("outfile.txt"); 
        String line;

        while((line = br.readLine()) != null)
        { 
            line = line.trim();
            line=line.replaceAll("\\s+", " ");
            fw.write(line);


        }
        fr.close();
        fw.close();
    }

}
public void readData() {
    
    File file = new File("file.txt"); //You can put your file name or your file position here 
    try {
    Scanner sc = new Scanner(file);
    
    while(sc.hasNext()) {
        System.out.println(sc.nextLine());
    } System.out.println();
    }
    catch (FileNotFoundException e) {
        System.out.println(e.getMessage());
    }
    
    System.out.println("End of the Main");
} //This will read it from a file and print on your console

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

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