簡體   English   中英

如何從java中的文件中讀取字符串和數字?

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

如何從文件中讀取字符串或數字,它們之間有一個空格。

您可以編寫一個類來讀取文件並刪除空格。

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