Я написал программу на Java для чтения в текстовом файле некоторых метаданных из изображений. Они содержат имена и длинный список из них иногда более 4000 имен. К сожалению, многие из этих имен совпадают, и поэтому я написал программу, которая берет список в файле .txt
, избавляется от дубликатов и выводит новый очищенный и отсортированный по алфавиту список в выходной текстовый файл.
Кроме того, программа добавляет теги списка HTML к каждому имени, чтобы я мог скопировать и вставить их в нужное место.
Пример текстового файла:
Chatty Little Kitty
Chatty Little Kitty
Bearly Nuf Taz
Got Lil Pepto
Однако, похоже, он не работает должным образом, так как в моем выходном файле все еще есть дубликаты. Однако код, который я написал, мне кажется правильным, поэтому я спрашиваю, есть ли проблема с тем, как я настраиваю свои операции чтения и записи.
Мой код:
* This program takes in a text file that has a bunch of words listed. It then creates a single alphabetically
* organized html list from that data. It also strips the data of dupblicates.
*/
import java.io.*;
import java.util.Arrays;
public class readItWriteIt
{
public static void main(String args[])
{
int MAX = 10000;
String[] lines = new String[MAX];
boolean valid = true;
try{
//Set up Input
FileInputStream fstream = new FileInputStream("test.txt");
DataInputStream in = new DataInputStream(fstream);
BufferedReader br = new BufferedReader(new InputStreamReader(in));
String strLine;
//Set up Output
FileWriter ostream = new FileWriter("out.txt");
BufferedWriter out = new BufferedWriter(ostream);
//counters
int count = 0;
int second_count = 0;
//start reading in lines from the file
while ((strLine = br.readLine()) != null){
//check to make sure that there aren't duplicates. If a line is the same as another line
//set boolean valid to false else set to true.
if((second_count++ > 0) && (count > 0)){
for(int i=0; i < count; i++)
{
if(lines[i].equals(strLine)){
valid = false;
}
else
{
valid = true;
}
}
}
//only copy the line to the local array if it is not a duplicate. Else do nothing with it.
if (valid == true){
lines[count] = strLine.trim();
count++;
}
else{}
second_count++;
}
//create a second array so that you can get rid of all the null values. It is the size of the
//used length in the first array called "lines"
String[] newlines = new String[count];
//copy data from array lines to array called newlines
for(int i = 0; i < count; i++){
newlines[i] = lines[i];
}
//sort the array alphabetically
Arrays.sort(newlines);
//write it out to file in alphabetical order along with the list syntax for html
for(int i = 0; i < count; i++)
{
out.write("<li>" + newlines[i] + "</li>");
out.newLine();
}
//close I/O
in.close();
out.close();
}catch (Exception e){//Catch exception if any
System.err.println("Error: " + e.getMessage());
}
}
}
Я написал это так
import java.util.HashSet;
import java.util.Set;
import java.io.*;
import java.util.Arrays;
public class converter {
public static void main(String[] args) {
try{
//Set up Input
FileInputStream fstream = new FileInputStream("test.txt");
DataInputStream in = new DataInputStream(fstream);
BufferedReader br = new BufferedReader(new InputStreamReader(in));
String strLine;
//Set up Output
FileWriter ostream = new FileWriter("out.txt");
BufferedWriter out = new BufferedWriter(ostream);
Set lines = new HashSet();
boolean result;
while ((strLine = br.readLine()) != null){
result = lines.add(strLine.trim());
}
String[] newlines = new String[lines.size()];
lines.toArray(newlines);
Arrays.sort(newlines);
//write it out to file in alphabetical order along with the list syntax for html
for(int i = 0; i < lines.size(); i++)
{
out.write("<li>" + newlines[i] + "</li>");
out.newLine();
}
out.close();
in.close();
}catch (Exception e){//Catch exception if any
System.err.println("Error: " + e.getMessage());
}
}
}
Но благодаря ewernli теперь он намного эффективнее.