如何打开并读取文件并将特定内容写入新文件?

How to open and read a file and write specific content to a new file?

第一周学习Java。为我下面的损坏代码道歉。试图打开一个文件读取它并选择需要的内容写入另一个文件。我的文件如下所示:

DESCRIPTION:
TITILE:
TYPE: image
SOURCE: Library
FORMAT: jpeg 
IDENTIFIER: 120034 
LATITUDE: 40.109580 
LONGITUDE: -88.228378 

DESCRIPTION: 
TITLE: GSLIS 
SUBJECT: 
TYPE: image 
SOURCE: Library 
FORMAT: jpeg 
IDENTIFIER: 120155 
LATITUDE: 40.107779 
LONGITUDE:-88.231621

我刚写了两段代码,一段打开阅读,一段匹配模式:

package Functions;

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

public class readFileLocal {
    private static final String[] String = null;
    private String path;

    public readFileLocal(String file_path){
        path = file_path;
    }

    public String[] openFile() throws IOException{  
        FileReader freader = new FileReader (path);
        BufferedReader textReader = new BufferedReader (freader);

        int numberOfLines = readLines();   
        String[] textData = new String[numberOfLines]; 

        int i;  
        for (i=0; i<numberOfLines; i++){

            String newLine=new String();
            newLine=null;
            textData[i] = textReader.readLine(); 
            String a = textData.toString();
            while ((textData[i])!=null){
                if (a.startsWith("Identifier: ") || a.startsWith("Latitude: ")||a.startsWith("Longitude:")){
                    newLine.append(a);
                }

                boolean filled1 =Boolean.valueOf(String newLine[0]);
                boolean filled2 =Boolean.valueOf(String newLine[1]);
                boolean filled3 =Boolean.valueOf(String newLine[2]);

                if(filled1, filled2, filled3) {
                       System.out.println(newLine[0]+'|'+newLine[1]+"|"+newLine[2]+"\n");
                }

                }
        }
    textReader.close();     
}


    int readLines() throws IOException{
        FileReader file_to_read = new FileReader(path);
        BufferedReader lines = new BufferedReader (file_to_read);

        String aLine=lines.readLine();
        int numberOfLines = 0;
        while(aLine != null) { 
            numberOfLines ++; 
        }  

        lines.close();
        return numberOfLines;
    }   

}

我还想出了如何在人们的帮助下以我想要的方式搜索字符串,如下所示:

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class ReadLatLong
{

    public ReadLatLong(){

       String line = "IDENTIFIER: 115956 LATITUDE: 40.104730 LONGITUDE: -88.228798 DATE RIGHTS IDENTIFIER: 115956 LATITUDE: 40.104730 LONGITUDE: -88.228798 DATE RIGHTS"; 
        String pattern = "IDENTIFIER:\s(\d*)\sLATITUDE:\s(\d*\.?\d*)\sLONGITUDE:\s(.*?)\s";

       Pattern r = Pattern.compile(pattern);
       Matcher m = r.matcher(line);

       while (m.find()) {
           System.out.println("Image: " + m.group(1)+"|"+m.group(2)+"|"+m.group(3));
       } 
   }
}

现在我想知道如何搜索整个文件以获取所有标识符、纬度、经度,然后像这样把它们全部放出来: 120034 | 40.109580 | -88.228378 \n 120155 | 40.107779 | -88.231621 \n

这是我的主要方法,但我也不知道如何将它写入新文件。

package readText;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;

public class FileData {

    public static void main(String[] args) throws Exception {

        String file_path1 = "F:\CampusImages.txt";
        String file_path2 = "F:\CampusImageIDs.txt";

        try{
            ReadFileLocal file = new ReadFileLocal(file_path1);
            WriteFile writeout = new WriteFile( file_path2); //Don't know how to write it in new file.
            PrintWriter writer = new PrintWriter(new FileWriter(new File(file_path2)));
            String[] arylines = file.openFile();
            writeout.WriteToFile(String.valueOf(arylines));

            int i;
            for (i=0; i<arylines.length; i++){
                System.out.println(arylines[i]);
            }   
       writer.close();  
        }

        catch(IOException e) { 
            System.out.println(e.getMessage()); 
        }
    }
}   

提前致谢。

看起来这是你的编程作业,所以我不会给你确切的编码。除非你的输入文件是空的,否则你的 readLines() 方法将永远循环。如果不是必须的,就不用算no。在阅读每一行之前。您可以执行以下操作:

read one line from the file
while the line is not null
    check if the line begins with one of the three identifier you want
    if so, append the line to a string
    if not, do nothing
    if the accumulated string has all three required line, use `ReadLatLong` to do an output
    (simplest way is to use 3 bool flags)
    read another line using the same variable name as at the beginning
end while

希望对您有所帮助。

编辑:好的,既然 RoverMAX 已经给出了他的编码,我给你另一个版本供你考虑。

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class TestCampusImages {

    static final String file_path1 = "CampusImages.txt";
    static final String file_path2 = "CampusImageIDs.txt";
    static final Pattern pID = Pattern.compile("(?<=IDENTIFIER:)[\d\s]*");
    static final Pattern pLAT = Pattern.compile("(?<=LATITUDE:)[\d\s-.]*");
    static final Pattern pLONG = Pattern.compile("(?<=LONGITUDE:)[\d\s-.]*");

    public static void main(String[] args) {
        int id = 0;
        float latitude = 0.0f, longitude = 0.0f;
        try {
            File inFile = new File(file_path1);
            BufferedReader textReader = new BufferedReader(new FileReader(inFile));
            File outFile = new File(file_path2);
            PrintWriter out = new PrintWriter(outFile);
            String inLine = textReader.readLine();
            while (inLine != null) {
                Matcher m = pID.matcher(inLine);
                if (m.find()) {
                    id = Integer.parseInt(m.group().trim());
                }
                m = pLAT.matcher(inLine);
                if (m.find()) {
                    latitude = Float.parseFloat(m.group().trim());
                }
                m = pLONG.matcher(inLine);
                if (m.find()) {
                    longitude = Float.parseFloat(m.group().trim());
                }
                if ((id!=0) && (latitude!=0.0f) && (longitude!=0.0f)) {
                    out.println(String.format("%d | %f | %f ", id,  latitude, longitude));
                    id = 0;
                    latitude = 0.0f; longitude = 0.0f;
                }//end if
                inLine = textReader.readLine();
            }//end while
            textReader.close();
            out.close();
        } catch (IOException e) {
            System.out.println(e.getMessage());
        }//end try
    } //end main

} //end TestCampusImages

此代码很好,因为它允许您在需要时进一步处理数据提取。但它没有对输入文件进行验证。所以要小心。如果您认为此处的任何回复有帮助,请将其标记为答案。

我通常这样做是逐行读取文件,然后逐行输出。我敢肯定还有其他方法可以做到这一点,只是试验一下。

try {
    FileReader fr = new FileReader(yourfile);
    BufferedReader br = new BufferedReader(fr);
    FileOutputStream fout = new FileOutputStream (yourOutputFile);
    PrintStream ps = new PrintStream(fout);
    String line = br.readLine();
    while (line != null) {
        //Do something; 
        String writeContent = your_code_to_get_write_content(line);
        ps.println(writeContent);
        line = br.readLine();
    }
} catch (IOException e) {
    System.out.println(e.getMessage());
}