I read two files (a large file and a small file)
The first file contains both capital letters and small letters
But second file contains just capital letters.
Program first extract capital letters from first(large file) file and then compare with second file (that contains just capital letters).
My code works well when the large files are small, But when my file size is about 400MB the program show an internal error "Java Out of Memory Error".
Here is my code:
public class SequenceComparator {
private ArrayList<Sequence> bigSequences;
private ArrayList<Sequence> smallSequences;
public SequenceComparator() {
bigSequences = new ArrayList<Sequence>();
smallSequences = new ArrayList<Sequence>();
}
private String splitUpperSequences(String bigSeq) {
StringBuilder sb = new StringBuilder();
for (char c : bigSeq.toCharArray()) {
if (Character.isLetter(c) && Character.isUpperCase(c)) {
sb.append(c);
}
}
return sb.toString();
}
public void readBigSequences() throws FileNotFoundException {
Scanner s = new Scanner(new FileReader("test_ref_Aviso_bristol_k_31_c_4.fa"));
while (s.hasNextLine()) {
String title = s.nextLine();
if (!title.startsWith(">")) {
continue;
}
String seq = s.nextLine();
Sequence sequence = new Sequence(title, splitUpperSequences(seq).trim());
bigSequences.add(sequence);
}
s.close();
}
public void readSmallSequences() throws FileNotFoundException {
Scanner s = new Scanner(new FileReader("SNP12K.fasta"));
while (s.hasNextLine()) {
String title = s.nextLine().trim();
if (!title.startsWith(">")) {
continue;
}
String seq = s.nextLine().trim();
Sequence sequence = new Sequence(title, seq);
smallSequences.add(sequence);
}
s.close();
}
public void printSeqArray(ArrayList<Sequence> seqArray) {
for (Sequence sequence : seqArray) {
System.out.println(sequence);
}
}
private void reportNotFoundSeqs(ArrayList<Sequence> notFoundSeqs) {
System.out.println("Sequence that is not similar with big file:\n\n");
printSeqArray(notFoundSeqs);
}
public void comparison() {
int bigLength = bigSequences.size();
int smallLength = smallSequences.size();
System.out.println("Sequences Length of big file is " + bigLength);
System.out.println("Sequences Length of small file is " + smallLength);
System.out.println("\n");
if (bigLength > smallLength) {
System.out.println("big file has " + (bigLength - smallLength) + " sequence more than smal file");
} else {
System.out.println("small file has " + (smallLength - bigLength) + " sequence more than big file");
}
System.out.println("\n");
int s = 0;
ArrayList<Sequence> notFoundSeqs = new ArrayList<Sequence>();
for (Sequence smalSeq : smallSequences) {
if (bigSequences.contains(smalSeq)) {
s++;
} else {
notFoundSeqs.add(smalSeq);
}
}
System.out.println("Tow files are similar in " + s + " point");
System.out.println("\n");
reportNotFoundSeqs(notFoundSeqs);
}
public ArrayList<Sequence> getBigSequences() {
return bigSequences;
}
public ArrayList<Sequence> getSmallSequences() {
return smallSequences;
}
static public void main(String args[]) throws FileNotFoundException {
SequenceComparator sc = new SequenceComparator();
System.out.println("Reading files...");
long befor = System.currentTimeMillis();
sc.readBigSequences();
System.out.println("\nBig file upper sequences:\n");
sc.printSeqArray(sc.getBigSequences());
sc.readSmallSequences();
sc.comparison();
long afer = System.currentTimeMillis();
System.out.println("Time: "+((afer-befor)/1000)+" Seconds"); }
class Sequence {
private String title;
private String seq;
public Sequence(String title, String seq) {
this.seq = seq;
this.title = title;
}
public Sequence() {
}
public String getSeq() {
return seq;
}
public void setSeq(String seq) {
this.seq = seq;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
#Override
public String toString() {
return "\nTitle: " + title + "\n" + "Sequence: " + seq + "\n";
}
#Override
public boolean equals(Object obj) {
Sequence other = (Sequence) obj;
return seq.equals(other.seq);
}
}
}
What can i do?
You are loading the whole file content into your memory. That's why you got the Out of Memory Error. Try instead to create a temp files of equal format and the compare both files line by line. Delete the temp file at the end.
Example:
private File prepareFile(String rawFirstFile) throws FileNotFoundException, IOException {
File tempFile = new File("rawFirstFile_temp.dat");
try(BufferedReader br = Files.newBufferedReader(new File(rawFirstFile).toPath());
BufferedWriter wr = Files.newBufferedWriter(tempFile.toPath(), StandardOpenOption.WRITE)){
String line = null;
while ((line = br.readLine()) != null) {
//
// change the raw line, save filtered data as new line in your temp file
// what ever you want. example:
// title1,seq1
// title2,seq2
// ...
//
wr.write(changeLine(line));
wr.newLine();
}
return tempFile;
}
}
public void compareFiles(String firstFile, String seconFile) throws FileNotFoundException, IOException{
File tempFirstFile = prepareFile(firstFile);
File secondFile = new File(seconFile); // maybe need to prepare too
try(BufferedReader br1 = Files.newBufferedReader(tempFirstFile.toPath());
BufferedReader br2 = Files.newBufferedReader(secondFile.toPath())){
String line1File = null;
String line2File = null;
// line by line
while ((line1File = br1.readLine()) != null && (line2File = br2.readLine()) != null ) {
//
// compare them
//
}
} finally {
if(tempFirstFile != null){
//tempFirstFile.deleteOnExit();
Files.delete(tempFirstFile.toPath()); // has no effect if deleteOnExit was called!
}
}
}
private String changeLine(String rawLine) {
//TODO
return rawLine;
}
edit: changed try-catch to try-with statement to get the answer more smarter
You should perform a byte by byte comparison, not line by line as mentioned by dit. If the source of the file is unknown, using readLine() is prone to attack.
Related
Changes: delete the first two characters of each word with the length of 4 and more characters
example: original 'qwerty', new 'erty'
A 'word' should be considered a continuous sequence of Cyrillic or Latin characters.
I wrote something like this, but output string is in line, but I need input text with indent characters.
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.Scanner;
public class Part1 {
// getting input string from the file
public static String getInput(String fileName) {
StringBuilder sb = new StringBuilder();
try {
Scanner scanner = new Scanner(new File(fileName), "UTF-8");
while (scanner.hasNextLine()) {
sb.append(scanner.nextLine()).append(System.lineSeparator());
}
scanner.close();
return sb.toString().trim();
} catch (IOException ex) {
ex.printStackTrace();
}
return sb.toString();
}
// deleting the first two characters of each word with the length of 4 and more characters
public static void convert() {
try (BufferedReader in = new BufferedReader(new FileReader("part1.txt"))) {
String line;
StringBuilder result = new StringBuilder();
while ((line = in.readLine()) != null) {
String[] wordsInLine = line.split("[.,!?\\-\\s\\n]+");
for (String string : wordsInLine) {
if (isLongerThanFour(string) && defineLocale(string) == "latn") {
result.append(string.substring(2) + " ");
} else if (isLongerThanFour(string) && defineLocale(string) == "cyrl") {
result.append(string.substring(4) + " ");
} else {
result.append(string + " ");
}
}
}
System.out.println(result);
}catch(IOException e){
e.getMessage();
}
}
// checking for right length of current word
public static boolean isLongerThanFour(String string){
return string.length() >= 4;
}
// define language of input word(one of cyrillic of latin languages)
private static String defineLocale(String string) {
char ch = string.charAt(0);
if (Character.isAlphabetic(ch)) {
if (Character.UnicodeBlock.of(ch).equals(Character.UnicodeBlock.CYRILLIC)) {
return "cyrl";
} else if (Character.UnicodeBlock.of(ch).equals(Character.UnicodeBlock.BASIC_LATIN)){
return "latn";
}
}
return "none";
}
public static void main(String[] args){
Part1.convert();
}
}
Can you point on my mistakes or suggest cleaner solution.
Thank you in advance.
public class Converter {
//helper enum
enum Language {
cyr,
lat,
none
}
// if you have to return more that two types of values then use enum
private static Language defineLocale(String string) {
char ch = string.charAt(0);
if (Character.isAlphabetic(ch)) {
if (Character.UnicodeBlock.of(ch).equals(Character.UnicodeBlock.CYRILLIC)) {
return Language.cyr;
} else if (Character.UnicodeBlock.of(ch).equals(Character.UnicodeBlock.BASIC_LATIN)){
return Language.lat;
}
}
return Language.none;
}
public void convert() {
try (BufferedReader in = new BufferedReader(new FileReader("part1.txt"))) {
String line;
StringBuilder result = new StringBuilder();
while ((line = in.readLine()) != null) {
String[] wordsInLine = line.split(" ");
for (String s : wordsInLine) {
if (s.length() > 3) {
switch (defineLocale(s)) {
case cyr:
result.append(s.substring(4));
break;
case lat:
result.append(s.substring(2));
break;
default:
result.append(s);
}
} else result.append(s);
result.append(" ");
}
result.append("\n");//all you were missing
}
System.out.println(result);
}catch(IOException e){
e.getMessage();
}
}
public static void main(String[] args){
new Converter().convert();
}
}
I hope this does not need any further explanation but dont be shy to ask if you dont understand something.
copy part like this(from date to date) I am trying to copy only a part of .CSV file based on the first column (Start Date and Time) data looks like (2019-01-28 10:22:00 AM) but the user have to put it like this (2019/01/28 10:22:00)
this is for windows, java opencsv , this is what I found but dont do what I need exaclty :
like this:
int startLine = get value1 from column csv ;
int endLine = get value2 from column csv;
public static void showLines(String fileName, int startLine, int endLine) throws IOException {
String line = null;
int currentLineNo = 1;
// int startLine = 20056;//40930;
// int currentLineNo = 0;
File currentDirectory = new File(new File(".").getAbsolutePath());
String fromPath = currentDirectory.getCanonicalPath() + "\\Target\\part.csv";
PrintWriter pw = null;
pw = new PrintWriter(new FileOutputStream(fromPath), true);
//pw.close();
BufferedReader in = null;
try {
in = new BufferedReader (new FileReader(fileName));
//read to startLine
while(currentLineNo<startLine) {
if (in.readLine()==null) {
// oops, early end of file
throw new IOException("File too small");
}
currentLineNo++;
}
//read until endLine
while(currentLineNo<=endLine) {
line = in.readLine();
if (line==null) {
// here, we'll forgive a short file
// note finally still cleans up
return;
}
System.out.println(line);
currentLineNo++;
pw.println(line);
}
} catch (IOException ex) {
System.out.println("Problem reading file.\n" + ex.getMessage());
}finally {
try { if (in!=null) in.close();
pw.close();
} catch(IOException ignore) {}
}
}
public static void main(String[] args) throws FileNotFoundException {
int startLine = 17 ;
int endLine = 2222;
File currentDirectory = new File(new File(".").getAbsolutePath());
try {
showLines(currentDirectory.getCanonicalPath() + "\\Sources\\concat.csv", startLine, endLine);
} catch (IOException e) {
e.printStackTrace();
}
// pw.println();
}
Common CSV format uses a comma as a delimiter, with quotations used to escape any column entry that uses them within the data. Assuming that your column one data is consistent with the format you posted, and that I wouldn't have to bother with quotations marks therefor, you could read the columns as:
public static void main(String[] args) {
//This is the path to the file you are writing to
String targetPath = "";
//This is the path to the file you are reading from
String inputFilePath = "";
String line = null;
ArrayList<String> lines = new ArrayList<String>();
boolean add = false;
String startLine = "2019/01/28 10:22:00";
String endLine = "2019/01/28 10:30:00";
String addFlagSplit[] = startLine.replace("/", "-").split(" ");
String addFlag = addFlagSplit[0] + " " + addFlagSplit[1];
String endFlagSplit[] = endLine.replace("/", "-").split(" ");
String endFlag = endFlagSplit[0] + " " + endFlagSplit[1];
try(PrintWriter pw = new PrintWriter(new FileOutputStream(targetPath), true)){
try (BufferedReader input = new BufferedReader(new FileReader(inputFilePath))){
while((line = input.readLine()) != null) {
String date = line.split(",")[0];
if(date.contains(addFlag)) {
add = true;
}else if(date.contains(endFlag)) {
break;
}
if(add) {
lines.add(line);
}
}
}
for(String currentLine : lines) {
pw.append(currentLine + "\n");
}
}catch(FileNotFoundException e) {
e.printStackTrace();
}catch(IOException e) {
e.printStackTrace();
}catch(Exception e) {
e.printStackTrace();
}
}
public static void main(String[] args) throws IOException {
File currentDirectory = new File(new File(".").getAbsolutePath());
String targetPath = currentDirectory.getCanonicalPath() + "\\Target\\part.csv";
String inputFilePath = currentDirectory.getCanonicalPath() + "\\Sources\\concat.csv";
String line = null;
ArrayList<String> lines = new ArrayList<String>();
boolean add = false;
String startLine = "2019/01/28 10:22:00";
String endLine = "2019/04/06 10:30:00";
try(PrintWriter pw = new PrintWriter(new FileOutputStream(targetPath), true)){
try (BufferedReader input = new BufferedReader(new FileReader(inputFilePath))){
while((line = input.readLine()) != null) {
String date = line.split(",")[0];
if(date.contains(startLine)) {
add = true;
}else if(date.contains(endLine)) {
break;
}
if(add) {
lines.add(line);
}
}
}
for(String currentLine : lines) {
pw.append(currentLine + "\n");
}
}catch(FileNotFoundException e) {
e.printStackTrace();
}catch(IOException e) {
e.printStackTrace();
}catch(Exception e) {
e.printStackTrace();
}
}
I am dividing my file into chunks but only problem i am facing is,
i have .srt file, but while doing chunks, it's cutting the characters i.e in first .srt file it's like 00:26:20,230 --> . in next file it continuing the next time stamp 00:27:40,343.
I need to check the timestamp to be complete and then next full subtitle sentence too. i.e if it's cutting the subtitle timesstamp or dialogue in in file, that tect to be append to next file. Please suggest me how can i achieve.
I am trying like below,
String FilePath = "/Users/meh/Desktop/escapeplan.srt";
FileInputStream fin = new FileInputStream(FilePath);
System.out.println("size: " +fin.getChannel().size());
long abc = 0l;
abc = (fin.getChannel().size())/3;
System.out.println("6: " +abc);
System.out.println("abc: " +abc);
//FilePath = args[1];
File filename = new File(FilePath);
long splitFileSize = 0,bytefileSize=0;
if (filename.exists()) {
try {
//bytefileSize = Long.parseLong(args[2]);
splitFileSize = abc;
Splitme spObj = new Splitme();
spObj.split(FilePath, (long) splitFileSize);
spObj = null;
} catch (Exception e) {
e.printStackTrace();
}
} else {
System.out.println("File Not Found....");
}
public void split(String FilePath, long splitlen) {
long leninfile = 0, leng = 0;
int count = 1, data;
try {
File filename = new File(FilePath);
InputStream infile = new BufferedInputStream(new FileInputStream(filename));
data = infile.read();
System.out.println("data");
System.out.println(data);
while (data != -1) {
filename = new File("/Users/meh/Documents/srt" + count + ".srt");
//RandomAccessFile outfile = new RandomAccessFile(filename, "rw");
OutputStream outfile = new BufferedOutputStream(new FileOutputStream(filename));
while (data != -1 && leng < splitlen) {
outfile.write(data);
leng++;
data = infile.read();
}
leninfile += leng;
leng = 0;
outfile.close();
changeTimeStamp(filename, count);
count++;
}
} catch (Exception e) {
e.printStackTrace();
}
}
i am trying to check the time stamp is in correct format or not. Then i need to check next line to be a dialogue and then the next line to be empty line. then it can stop chunk or else it should append the text from the previous chunk to next chunk file in the beginning of line . so that it may get in correct format.
I tried checking the format like,
while ((strLine = br.readLine()) != null) {
String[] atoms = strLine.split(" --> ");
if (atoms.length == 1) {
out.write(strLine + "\n");
} else {
String startTS = atoms[0];
String endTS = atoms[1];
System.out.print("sri atmos start" + startTS);
System.out.print("sri atmos end" + endTS);
SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss,SSS");
sdf.setLenient(false);
try
{
sdf.parse(startTS);
sdf.parse(endTS);
System.out.println("Valid time");
System.out.println("File path" + srcFileNm);
}
catch(Exception e) {
System.out.println("Invalid time");
System.out.println("Exception start" + startTS);
System.out.println("Exception end" + endTS);
}
}
some screens of my output chunks,
Help me how can i make this possible.
I think you should change approach, and fully use basic I/O methods. I tried to encapsulate logic in a small class, that produces a triple with id, msecs and a list of subtitles (if I'm not wrong, you can have more than a line). Then I leaved the remainder externally. Chunker is a class that reads a triple (class Three) from file, so that you can manage it and write it somewhere.
This is just a "quick&dirty" idea that you can refine, but it should work.
package org.norsam.stackoverflow;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
public class Chunker
{
BufferedReader r;
int chunk = 0;
File dir;
public Chunker(File dir, String filename) throws IOException
{
File f = new File(dir, filename);
this.dir = dir;
this.r = new BufferedReader(new FileReader(f));
}
public Three readThree() throws IOException
{
Integer id = Integer.parseInt(r.readLine());
String msecs = r.readLine();
String s = null;
List<String> srt = new ArrayList<>();
while (!(s = r.readLine().trim()).isEmpty()) {
srt.add(s);
}
return new Three(id, msecs, srt);
}
class Three
{
Integer id;
String msecs;
List<String> srts;
Three(Integer id, String msecs, List<String> srts)
{
this.id = id;
this.msecs = msecs;
this.srts = srts;
}
Three doSomething() {
// here you can do something with your data,
// e.g. split msecs on "-->" and check times
return this;
}
void write(BufferedWriter r) throws IOException
{
r.write(id);
r.newLine();
r.write(msecs);
r.newLine();
for (String s : srts) {
r.write(s);
r.newLine();
}
r.newLine();
}
}
public static void main(String[] args) throws IOException
{
String baseDir = "/dir/where/resides/srt";
String filename = "filename.srt";
int elemPerChunk = 50;
int fileNum = 0;
File dir = new File(baseDir);
Chunker chunker = new Chunker(dir, filename);
boolean completed = false;
while (!completed) {
int srtCount = 0;
File f = new File(baseDir, "ch." + (fileNum++) + "." + filename);
BufferedWriter w = new BufferedWriter(new FileWriter(f));
try {
while (srtCount++ < elemPerChunk) {
chunker.readThree().doSomething().write(w);
}
} catch (NullPointerException e) {
completed = true;
}
w.close();
}
}
}
I am having this issue getting the file input from one class and using it in another. So what happens is I have a file called readFile.java that reads in the line of a txt file. I have another file that I am using to evaluate a stack that I want to use the file input. So all in all, I am trying to find a way to replace my testInput string in my evalStack.java file with the file input from the readFile.java.
Here is the readFile.java:
import java.util.Scanner;
import java.io.*;
public class readFile {
String fname;
public readFile() {
System.out.println("Constructor");
getFileName();
readFileContents();
}
public void readFileContents()
{
boolean looping;
DataInputStream in;
String line;
int j, len;
char ch;
/* Read input from file and process. */
try {
in = new DataInputStream(new FileInputStream(fname));
looping = true;
while(looping) {
/* Get a line of input from the file. */
if (null == (line = in.readLine())) {
looping = false;
/* Close and free up system resource. */
in.close();
}
else {
System.out.println("line = "+line);
j = 0;
len = line.length();
for(j=0;j<len;j++){
System.out.println("line["+j+"] = "+line.charAt(j));
}
}
} /* End while. */
} /* End try. */
catch(IOException e) {
System.out.println("Error " + e);
} /* End catch. */
}
public void getFileName()
{
Scanner in = new Scanner(System.in);
System.out.println("Enter file name please.");
fname = in.nextLine();
System.out.println("You entered "+fname);
}
}
This is the evalStack.java:
import java.util.Scanner;
import java.io.*;
public class evalStack {
static String testInput = "(6+3) + (3-2)";
//This is the line I want to replace with the input the readFile gives me.
public static void main(String[] args){
int maxLength = testInput.length();
stackOb eval = new stackOb(maxLength);
boolean test = false;
//Evaluate and check parenthesis
for(int i = 0; i < testInput.length(); i++)
{
char a = testInput.charAt(i);
if(a=='(')
{
eval.push(a);
}
else if(a==')')
{
if(eval.empty() == false)
{
eval.pop();
}
else
{
test = true;
System.out.println("The equation is a not valid one.");
System.exit(0);
}
}
else
{
continue;
}
}
if(eval.empty() == true && test == false)
{
System.out.println("The equation is a valid one.");
}
else
{
System.out.println("The equation is a not valid one.");
}
}
Add the line import readFile; to the top of evalStack.java
Change input: static String testInput = new readFile().readFileContents();
Change return type: public String readFileContents()
Replace j = 0; with return line;
That will make it evaluate the first line.
I´m creating an arraylist in my
UserArchive class and add User-objects from my User class:
public class UserArchive implements Serializable {
ArrayList<User> list = new ArrayList<User>();
// Inserts a new User-object
public void regCustomer(User u) {
list.add(u);
}
What is the best way to read and write this list?
I think this is the right way to write it?
public void writeFile() {
File fileName = new File("testList.txt");
try{
FileWriter fw = new FileWriter(fileName);
Writer output = new BufferedWriter(fw);
int sz = list.size();
for(int i = 0; i < sz; i++){
output.write(list.get(i).toString() +"\n");
}
output.close();
} catch(Exception e){
JOptionPane.showMessageDialog(null, "Kan ikke lage denne filen");
}
I´ve tried using BufferedReader to read the file, but can't get list.add(line) to work:
public void readFile() {
String fileName = "testList.txt";
String line;
try{
BufferedReader input = new BufferedReader(new FileReader(fileName));
if(!input.ready()){
throw new IOException();
}
while((line = input.readLine()) != null){
list.add(line);
}
input.close();
} catch(IOException e){
System.out.println(e);
}
}
I know the problem is that line is a String and should some how be a User. Is the problem that I cant use BufferedReader to do this? If so, how am I suppose to read the file?
The simplest way to do it is convert each user to csv format provided the user object is not complex.
For example your user class should look like this
public class User {
private static final String SPLIT_CHAR = ",";
private String field1;
private String field2;
private String field3;
public User(String csv) {
String[] split = csv.split(SPLIT_CHAR);
if (split.length > 0) {
field1 = split[0];
}
if (split.length > 1) {
field2 = split[1];
}
if (split.length > 2) {
field3 = split[2];
}
}
/**
* Setters and getters for fields
*
*
*/
public String toCSV() {
//check null here and pass empty strings
return field1 + SPLIT_CHAR + field2 + SPLIT_CHAR + field3;
}
}
}
While writing the object call
output.write(list.get(i).toCSV() +"\n");
and when reading you can call
list.add(new User(line));
Imagine a simple User class, like so:
public class User {
private int id;
private String username;
// Constructors, etc...
public String toString() {
StringBuilder sb = new StringBuilder("#USER $");
sb.append(id);
sb.append(" $ ");
sb.append(username);
return sb.toString();
}
}
For an user with id = 42 and username = "Dummy", the user String representation would be:
#USER $ 42 $ Dummy
At first glance, your code seems to successfully write these strings to a text file (I haven't tested it yet).
So, the problem lies in reading back the information. This, extracting meaningful information from (in this case) formatted text, is commonly known as parsing.
You want to parse this information, from the lines you read.
Adapting your code:
BufferedReader input = null;
try {
input = new BufferedReader(new FileReader(fileName));
String line;
while((line = input.readLine()) != null) {
list.add(User.parse(line));
}
} catch(IOException e) {
e.printStackTrace();
} finally {
if (input != null) { input.close(); }
}
Note the subtle difference. I've replaced list.add(line) with list.add(User.parse(line)). This is where the magic occurs. Let's go on and implement the parsing method.
public class User {
private int id;
private String username;
// ...
public static User parse(String line) throws Exception {
// Let's split the line on those $ symbols, possibly with spaces.
String[] info = line.split("[ ]*\\$[ ]*");
// Now, we must validate the info gathered.
if (info.length != 3 || !info[0].equals("#USER")) {
// Here would go some exception defined by you.
// Alternatively, handle the error in some other way.
throw new Exception("Unknown data format.");
}
// Let's retrieve the id.
int id;
try {
id = Integer.parseInt(info[1]);
} catch (NumberFormatException ex) {
throw new Exception("Invalid id.");
}
// The username is a String, so it's ok.
// Create new User and return it.
return new User(id, info[2]);
}
}
And you're done!