2015-03-19 139 views
1

第一周学习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()); 
     } 
    } 
} 

在此先感谢。

回答

0

看起来这是你的编程作业,所以我不会给你确切的编码。除非你的输入文件是空的,否则你的readLines()方法将永远循环。如果它不是必须的,那么你不需要数数。在阅读其中的每一行之前,请阅读。这里是你可以做的:

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 

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

+0

不,这不是我的家庭作业。这只是我试图做的一个项目,同时也是在挑选Java。我在学校学了一个小蟒蛇,那是我用来理解Java的镜头,但我的Python也很基础。 :-P无论如何,谢谢你的线索。 – qximin 2015-03-19 03:04:25

+0

对不起,我使用的不适当的措辞。最近发生了不合理的事情。我回想起当我开始使用Java时,曾经在其他人使用javadoc发送给我的示例代码中查看每个单词。如果你有时间,你可以考虑在javadoc中查询语句及其含义。这对我的情况有很大的帮助。 – senderj 2015-03-19 05:55:02

+0

谢谢。我正在阅读不同的资源。我喜欢用于学习的是其他人的代码。我喜欢阅读定义,示例代码和详细解释,以便我能更好地理解事物。 – qximin 2015-03-19 14:46:26

0

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

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

我试过这段代码,但总是有一行'fout.println(writeContent)'的错误;错误消息是:'方法println(String)对于FileOutputStream类型是未定义的。 – qximin 2015-03-20 00:06:11

+0

应该是ps.println – RoverMAX 2015-03-20 00:07:10

相关问题