FASTA format: Difference between revisions
Content added Content deleted
(Realize in F#) |
|||
Line 968: | Line 968: | ||
=={{header|Java}}== |
=={{header|Java}}== |
||
This implementation presumes the data-file is well-formed |
|||
<syntaxhighlight lang="java"> |
|||
import java.io.BufferedReader; |
|||
import java.io.FileReader; |
|||
import java.io.IOException; |
|||
import java.util.ArrayList; |
|||
import java.util.List; |
|||
</syntaxhighlight> |
|||
<syntaxhighlight lang="java"> |
|||
public static void main(String[] args) throws IOException { |
|||
List<FASTA> fastas = readFile("fastas.txt"); |
|||
for (FASTA fasta : fastas) |
|||
System.out.println(fasta); |
|||
} |
|||
static List<FASTA> readFile(String path) throws IOException { |
|||
try (BufferedReader reader = new BufferedReader(new FileReader(path))) { |
|||
List<FASTA> list = new ArrayList<>(); |
|||
StringBuilder lines = null; |
|||
String newline = System.lineSeparator(); |
|||
String line; |
|||
while ((line = reader.readLine()) != null) { |
|||
if (line.startsWith(">")) { |
|||
if (lines != null) |
|||
list.add(parseFASTA(lines.toString())); |
|||
lines = new StringBuilder(); |
|||
lines.append(line).append(newline); |
|||
} else { |
|||
lines.append(line); |
|||
} |
|||
} |
|||
list.add(parseFASTA(lines.toString())); |
|||
return list; |
|||
} |
|||
} |
|||
static FASTA parseFASTA(String string) { |
|||
String description; |
|||
char[] sequence; |
|||
int indexOf = string.indexOf(System.lineSeparator()); |
|||
description = string.substring(1, indexOf); |
|||
/* using 'stripLeading' will remove any additional line-separators */ |
|||
sequence = string.substring(indexOf + 1).stripLeading().toCharArray(); |
|||
return new FASTA(description, sequence); |
|||
} |
|||
/* using a 'char' array seems more logical */ |
|||
record FASTA(String description, char[] sequence) { |
|||
@Override |
|||
public String toString() { |
|||
return "%s: %s".formatted(description, new String(sequence)); |
|||
} |
|||
} |
|||
</syntaxhighlight> |
|||
<pre> |
|||
Rosetta_Example_1: THERECANBENOSPACE |
|||
Rosetta_Example_2: THERECANBESEVERALLINESBUTTHEYALLMUSTBECONCATENATED |
|||
</pre> |
|||
<br /> |
|||
An alternate demonstration |
|||
{{trans|D}} |
{{trans|D}} |
||
{{works with|Java|7}} |
{{works with|Java|7}} |