Im trying to read username and password from .txt file in Java.
Format of file is as following:
user1:pass1
user2:pass2
user3:pass3
My code can't properly read passwords, any hints?
EDIT: also missing last password because last \n is missing, any way to repair it instead of adding extra newline to txt file?
try {
FileReader fileReader = new FileReader(filename);
BufferedReader bufferedReader = new BufferedReader(fileReader);
int c;
String user = "";
String pass = "";
char helper = 0;
while(( c = bufferedReader.read()) != -1 ) {
System.out.println((char)c);
if((char)c == '\n') {
ftpServer.addUser(user, pass);
//System.out.printf("%s", pass);
user = "";
pass = "";
helper = 0;
} else {
if ((char) c == ':') {
helper = ':';
}
if (helper == 0) {
user += (char) c;
}
if (helper == ':') {
if ((char) c != ':')
pass += (char) c;
}
}
}
bufferedReader.close();
}
If using JAVA: 8 and 8+ you could use stream on Files - java.nio.files
Path path = Paths.get(filename);
try (Stream<String> lines = Files.lines(path)) {
lines.forEach(s -> {
if (s.contains(":")) {
String[] line = s.split(":");
String userName = line[0];
String pass = line[1];
System.out.println("User name: " + userName + " password: " + pass);
}
});
} catch (IOException ex) {
// do something or re-throw...
}
Or use BufferedReader
BufferedReader reader;
try {
reader = new BufferedReader(new FileReader("/Users/kants/test.txt"));
String lineInFile = reader.readLine();
while (lineInFile != null) {
if (lineInFile.contains(":")) {
String[] line = lineInFile.split(":");
String userName = line[0];
String pass = line[1];
System.out.println("User name: " + userName + " password: " + pass);
}
lineInFile = reader.readLine();
}
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
NOTE: You must add further null checks and try-catch handlings. Above code is just to show you the logic.
I dont think you need an additional loop
public static void main(String[] args) throws IOException {
BufferedReader reader;
try {
reader = new BufferedReader(new FileReader(
"path/to/file"));
String line = reader.readLine();
while (line != null) {
System.out.println(line);
// read next line
line = reader.readLine();
if (line.contains(":")) {
String user = line.split(":")[0];
String pass = line.split(":")[1];
System.out.println("User is " + user + "Password is " + pass);
} }
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
prints
user1:pass1
User is user2Password is pass2
user2:pass2
User is user3Password is pass3
user3:pass3
Here is an elaborated implementation -
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.HashSet;
import java.util.Set;
import java.util.stream.Stream;
public class ReadFileAsStream {
public static void main(String... arguments) {
CredentialsParser parser;
try {
parser = new CredentialsParser("c:/temp/credtest.txt");
Credential[] credentials = parser.getCredentials();
for (Credential credential : credentials) {
System.out.println(String.format("%s : %s", credential.getUsername(), credential.getPassword()));
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
//Parser for the credentials file format
class CredentialsParser {
private Set<Credential> credentials = new HashSet<>();
String filename = null;
public CredentialsParser() {
super();
}
public CredentialsParser(String filename) throws IOException {
super();
setFilename(filename);
if (getFilename() != null) {
parseCredentialsFile();
}
}
public Credential[] getCredentials() {
return credentials.toArray(new Credential[credentials.size()]);
}
// method to add credentials
public void addCredential(String entry) {
if (entry.indexOf(':') > -1) {
String[] values = entry.split(":");
credentials.add(new Credential(values[0], values[1]));
}
}
public String getFilename() {
return filename;
}
public void setFilename(String filename) {
this.filename = filename;
}
protected void parseCredentialsFile() throws IOException {
// read file into stream, try-with-resources
try (Stream<String> stream = Files.lines(Paths.get(filename))) {
stream.forEach(this::addCredential);
}
}
}
// Value holder for each credential entry
class Credential {
private String username = null;
private String password = null;
public Credential() {
super();
}
public Credential(String username, String password) {
super();
this.username = username;
this.password = password;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
}
Please modify your code to this :
Use split method to make your work easy :)
public class Example {
public static void main(String[] args) {
BufferedReader reader;
try {
reader = new BufferedReader(new FileReader("F://test.txt"));
String line = reader.readLine();
while (line != null) {
String[] lineParts = line.split(":");
System.out.println("user : " + lineParts[0]);
System.out.println("password : " + lineParts[1]);
line = reader.readLine();
}
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
In test.txt :
user1:pass1
user2:pass2
user3:pass3
Output :
user : user1
password : pass1
user : user2
password : pass2
user : user3
password : pass3
Related
I found this great Java Bean that allows you to send an html email including attachments via a managed java bean. It works as described when I use it directly form an Xpage.
However, I would like to use this in the backend in a scheduled agent. The problem I have run into is when I try to pass a document to the java bean. The bean is expecting (I think) an XSP document, which I don't have when in the back end, so it throws an error.
I thought I would just send the UNID of the document that I want and then change it so it would work with this bean, however, when I try to set the UNID I get an error:
Unknown member 'setUNID' in Java class 'com.scoular.utls.Email'
I am confused. Seems like this has something to do with a wrapped document, but don't understand.
Here is the faces-config:
<faces-config>
<managed-bean>
<managed-bean-name>Email</managed-bean-name>
<managed-bean-class>com.scoular.utls.Email</managed-bean-class>
<managed-bean-scope>request</managed-bean-scope>
<managed-property>
<property-name>debugMode</property-name>
<value>true</value>
</managed-property>
</managed-bean>
</faces-config>
Here is a button I am using to test calling the method:
//Need to get email document
var emlView = database.getView("xpViewEmailsAll");
var emlDoc = emlView.getFirstDocument();
if (emlDoc != null) {
//try{
var subject = ""
var senderEmail = supEml
var senderName = supNme
Email.setSendTo("John");
Email.setSubject("subject");
Email.setSenderEmail("John#gmal.com");
Email.setUNID = emlDoc.getUniversalID();
Email.setSenderName("Sender");
//Email.setBackEndDocument(emlDoc);
Email.setFieldName("Body");
Email.send();
//}catch(e){
//print(e.getMessage());
//}
}
And here is the bean:
package com.scoular.utls;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.faces.context.FacesContext;
import lotus.domino.Database;
import lotus.domino.Document;
import lotus.domino.EmbeddedObject;
import lotus.domino.MIMEEntity;
import lotus.domino.MIMEHeader;
import lotus.domino.NotesException;
import lotus.domino.Session;
import lotus.domino.Stream;
import com.ibm.commons.util.NotImplementedException;
import com.ibm.domino.xsp.module.nsf.NotesContext;
import com.ibm.xsp.model.FileRowData;
import com.ibm.xsp.model.domino.wrapped.DominoDocument;
import com.ibm.xsp.model.domino.wrapped.DominoRichTextItem;
import com.ibm.xsp.model.domino.wrapped.DominoDocument.AttachmentValueHolder;
import com.ibm.xsp.persistence.PersistedContent;
public class Email {
private ArrayList<String> sendTo;
private ArrayList<String> ccList;
private ArrayList<String> bccList;
private String senderEmail;
private String senderName;
private String subject;
private DominoDocument document;
private String fieldName;
private String bannerHTML;
private String footerHTML;
private String unid;
private boolean debugMode = false;
private static final Pattern imgRegExp = Pattern.compile("<img[^>]+src\\s*=\\s*['\"]([^'\"]+)['\"][^>]*>");
// -------------------------------------------------------------------------
public Email() {
this.subject = "";
this.sendTo = new ArrayList<String>();
this.ccList = new ArrayList<String>();
this.bccList = new ArrayList<String>();
}
// -------------------------------------------------------------------------
public String getSendTo() {
if (this.isDebugMode()) {
System.out.println("getSendTo() : " + this.sendTo.toString());
}
return this.sendTo.toString().replace("[", "").replace("]", "");
}
public void setSendTo(final String sendTo) {
this.sendTo.add(sendTo);
}
// -------------------------------------------------------------------------
public String getCcList() {
if (this.isDebugMode()) {
System.out.println("getCcList() : " + this.ccList.toString());
}
return this.ccList.toString().replace("[", "").replace("]", "");
}
public void setCcList(final String ccList) {
this.ccList.add(ccList);
}
// -------------------------------------------------------------------------
public String getBccList() {
if (this.isDebugMode()) {
System.out.println("getBccList() : " + this.bccList.toString());
}
return this.bccList.toString().replace("[", "").replace("]", "");
}
public void setBccList(final String bccList) {
this.bccList.add(bccList);
}
// -------------------------------------------------------------------------
public String getSenderEmail() {
return this.senderEmail;
}
public void setSenderEmail(final String senderEmail) {
this.senderEmail = senderEmail;
}
// -------------------------------------------------------------------------
public String getSenderName() {
return this.senderName;
}
public void setSenderName(final String senderName) {
this.senderName = senderName;
}
// -------------------------------------------------------------------------
public String getSubject() {
return this.subject;
}
public void setSubject(final String subject) {
this.subject = subject;
}
// -------------------------------------------------------------------------
public boolean isDebugMode() {
return this.debugMode;
}
public void setDebugMode(final boolean debugMode) {
this.debugMode = debugMode;
}
// -------------------------------------------------------------------------
private Session getCurrentSession() {
NotesContext nc = NotesContext.getCurrentUnchecked();
return (null != nc) ? nc.getCurrentSession() : null;
}
// -------------------------------------------------------------------------
private Database getCurrentDatabase() {
NotesContext nc = NotesContext.getCurrentUnchecked();
return (null != nc) ? nc.getCurrentDatabase() : null;
}
// -------------------------------------------------------------------------
public void send() throws NotesException, IOException, Exception {
Session session = getCurrentSession();
Database database = getCurrentDatabase();
if (null != session && null != database && null != this.sendTo && null != this.subject
&& null != this.senderEmail) {
try {
if (this.isDebugMode()) {
System.out.println("Started send()");
}
session.setConvertMime(false);
Document emailDocument = database.createDocument();
MIMEEntity emailRoot = emailDocument.createMIMEEntity("Body");
if (null != emailRoot) {
MIMEHeader emailHeader = emailRoot.createHeader("Reply-To");
emailHeader.setHeaderVal(this.getSenderEmail());
emailHeader = emailRoot.createHeader("Return-Path");
emailHeader.setHeaderVal(this.getSenderEmail());
final String fromSender = (null == this.getSenderName()) ? this.getSenderEmail() : "\""
+ this.getSenderName() + "\" <" + this.getSenderEmail() + ">";
emailHeader = emailRoot.createHeader("From");
emailHeader.setHeaderVal(fromSender);
emailHeader = emailRoot.createHeader("Sender");
emailHeader.setHeaderVal(fromSender);
emailHeader = emailRoot.createHeader("To");
emailHeader.setHeaderVal(this.getSendTo());
if (!this.ccList.isEmpty()) {
emailHeader = emailRoot.createHeader("CC");
emailHeader.setHeaderVal(this.getCcList());
}
if (!this.bccList.isEmpty()) {
emailHeader = emailRoot.createHeader("BCC");
emailHeader.setHeaderVal(this.getBccList());
}
emailHeader = emailRoot.createHeader("Subject");
emailHeader.setHeaderVal(this.getSubject());
MIMEEntity emailRootChild = emailRoot.createChildEntity();
if (null != emailRootChild) {
final String boundary = System.currentTimeMillis() + "-" + this.document.getDocumentId();
emailHeader = emailRootChild.createHeader("Content-Type");
emailHeader.setHeaderVal("multipart/alternative; boundary=\"" + boundary + "\"");
MIMEEntity emailChild = emailRootChild.createChildEntity();
if (null != emailChild) {
final String contentAsText = this.document.getRichTextItem(this.fieldName)
.getContentAsText();
Stream stream = session.createStream();
stream.writeText(contentAsText);
emailChild.setContentFromText(stream, "text/plain; charset=\"UTF-8\"", MIMEEntity.ENC_NONE);
stream.close();
emailChild = emailRootChild.createChildEntity();
stream = session.createStream();
stream.writeText(this.getHTML());
emailChild.setContentFromText(stream, "text/html; charset=\"UTF-8\"", MIMEEntity.ENC_NONE);
stream.close();
stream.recycle();
stream = null;
}
// add embedded images....
final List<FileRowData> embeddedImages = this.getEmbeddedImagesList();
if (null != embeddedImages && !embeddedImages.isEmpty()) {
if (this.isDebugMode()) {
System.out.println("Adding Embedded Images...");
}
for (FileRowData embeddedImage : embeddedImages) {
emailRootChild = emailRoot.createChildEntity();
if (null != emailRootChild && embeddedImage instanceof AttachmentValueHolder) {
InputStream is = null;
try {
String persistentName = ((AttachmentValueHolder) embeddedImage)
.getPersistentName();
String cid = ((AttachmentValueHolder) embeddedImage).getCID();
emailHeader = emailRootChild.createHeader("Content-Disposition");
emailHeader.setHeaderVal("inline; filename=\"" + persistentName + "\"");
emailHeader = emailRootChild.createHeader("Content-ID");
emailHeader.setHeaderVal("<" + cid + ">");
is = this.getEmbeddedImageStream(persistentName);
Stream stream = session.createStream();
stream.setContents(is);
emailRootChild.setContentFromBytes(stream, embeddedImage.getType(),
MIMEEntity.ENC_IDENTITY_BINARY);
if (this.isDebugMode()) {
System.out.println("Added Embedded Image : " + persistentName);
}
} catch (IOException e) {
if (this.isDebugMode()) {
System.out.println("Adding Embedded Image failed : " + e.getMessage());
}
throw e;
} finally {
if (null != is) {
is.close();
is = null;
}
}
}
}
if (this.isDebugMode()) {
System.out.println("Completed Adding Embedded Images");
}
}
// add attachments....
final List<FileRowData> attachments = this.getDocument().getAttachmentList(this.getFieldName());
if (null != attachments && !attachments.isEmpty()) {
if (this.isDebugMode()) {
System.out.println("Adding Attachments...");
}
for (FileRowData attachment : attachments) {
emailRootChild = emailRoot.createChildEntity();
if (null != emailRootChild && attachment instanceof AttachmentValueHolder) {
InputStream is = null;
try {
String persistentName = ((AttachmentValueHolder) attachment)
.getPersistentName();
String cid = ((AttachmentValueHolder) attachment).getCID();
EmbeddedObject eo = this.getDocument().getDocument().getAttachment(
persistentName);
if (null != eo) {
emailHeader = emailRootChild.createHeader("Content-Disposition");
emailHeader.setHeaderVal("attachment; filename=\"" + persistentName + "\"");
emailHeader = emailRootChild.createHeader("Content-ID");
emailHeader.setHeaderVal("<" + cid + ">");
is = eo.getInputStream();
Stream stream = session.createStream();
stream.setContents(is);
emailRootChild.setContentFromBytes(stream, attachment.getType(),
MIMEEntity.ENC_IDENTITY_BINARY);
if (this.isDebugMode()) {
System.out.println("Added Attachment : " + persistentName);
}
}
} catch (Exception e) {
if (this.isDebugMode()) {
System.out.println("Adding Attachment failed : " + e.getMessage());
}
throw e;
} finally {
if (null != is) {
is.close();
is = null;
}
}
}
}
if (this.isDebugMode()) {
System.out.println("Completed Adding Attachments");
}
}
}
}
emailDocument.send();
session.setConvertMime(true);
if (this.isDebugMode()) {
System.out.println("Completed send()");
}
} catch (NotesException e) {
if (this.isDebugMode()) {
System.out.println("Failed send() with NotesException" + e.getMessage());
}
throw e;
} catch (IOException e) {
if (this.isDebugMode()) {
System.out.println("Failed send() with IOException" + e.getMessage());
}
throw e;
} catch (Exception e) {
if (this.isDebugMode()) {
System.out.println("Failed send() with Exception" + e.getMessage());
}
throw e;
}
}
}
// -------------------------------------------------------------------------
public DominoDocument getDocument() {
return this.document;
}
public void setDocument(final DominoDocument document) {
this.document = document;
}
// -------------------------------------------------------------------------
// -------------------------------------------------------------------------
public String getFieldName() {
return this.fieldName;
}
public void setFieldName(final String fieldName) {
this.fieldName = fieldName;
}
// -------------------------------------------------------------------------
public List<FileRowData> getEmbeddedImagesList() throws NotesException {
if (null != document && null != fieldName) {
return document.getEmbeddedImagesList(fieldName);
}
return null;
}
// -------------------------------------------------------------------------
private InputStream getEmbeddedImageStream(final String fileName) throws NotesException, IOException {
if (null != document && null != fieldName && null != fileName) {
final DominoRichTextItem drti = document.getRichTextItem(fieldName);
if (null != drti) {
final PersistedContent pc = drti.getPersistedContent(FacesContext.getCurrentInstance(), fieldName,
fileName);
if (null != pc) {
return pc.getInputStream();
}
}
}
return null;
}
// -------------------------------------------------------------------------
public String getHTML() {
StringBuffer html = new StringBuffer();
html.append(getBannerHTML());
html.append(getBodyHTML());
html.append(getFooterHTML());
return html.toString();
}
// -------------------------------------------------------------------------
public String getBannerHTML() {
return this.bannerHTML;
}
public void setBannerHTML(final String bannerHTML) {
this.bannerHTML = bannerHTML;
}
// -------------------------------------------------------------------------
public String getBodyHTML() {
if (null != document && null != fieldName) {
if (this.isDebugMode()) {
System.out.println("Started getBodyHTML()");
}
final DominoRichTextItem drti = document.getRichTextItem(fieldName);
if (null != drti) {
try {
String html = drti.getHTML();
if (null != html) {
final List<FileRowData> fileRowDataList = document.getEmbeddedImagesList(fieldName);
if (null != fileRowDataList) {
final Matcher matcher = imgRegExp.matcher(html);
while (matcher.find()) {
String src = matcher.group();
final String srcToken = "src=\"";
final int x = src.indexOf(srcToken);
final int y = src.indexOf("\"", x + srcToken.length());
final String srcText = src.substring(x + srcToken.length(), y);
for (FileRowData fileRowData : fileRowDataList) {
final String srcImage = fileRowData.getHref();
final String cidImage = ((AttachmentValueHolder) fileRowData).getCID();
if (srcText.endsWith(srcImage)) {
final String newSrc = src.replace(srcText, "cid:" + cidImage);
html = html.replace(src, newSrc);
if (this.isDebugMode()) {
System.out.println("CID referenced image: " + srcText + " with CID:"
+ cidImage);
}
}
}
}
}
}
if (this.isDebugMode()) {
System.out.println("Completed getBodyHTML() : " + html);
}
return html;
} catch (Exception e) {
if (this.isDebugMode()) {
System.out.println("Failed getBodyHTML() : " + e.getMessage());
}
}
}
}
return null;
}
public void setBodyHTML(final String bodyHTML) throws NotImplementedException {
if (this.isDebugMode()) {
System.out.println("Method setBodyHTML(string) is not permitted");
}
throw new NotImplementedException();
}
// -------------------------------------------------------------------------
public String getFooterHTML() {
return this.footerHTML;
}
public void setFooterHTML(final String footerHTML) {
this.footerHTML = footerHTML;
}
public String getUnid() {
return unid;
}
public void setUnid(final String unid) {
this.unid = unid;
}
// -------------------------------------------------------------------------
} // end EmailBean
The Email.setUNID statement is wrong. Try:
Email.setUnid(emlDoc.getUniversalID());
I try to execute the startUp method when i deploy my web services, but doesn`t work.
I'm using:
windows 7
tomcat 8.0.30
axis2 1.7.0
I've tryed to deploy my service as a pojo service also i try generating the *.aar and placing it in:
apache-tomcat-8.0.30\webapps\axis2\WEB-INF\services
but when i run the tomcat, and deploy this and other services, the startUp method dont launch.
this is my code:
import java.io.*;
import java.util.*;
import org.apache.axis2.context.ConfigurationContext;
import org.apache.axis2.description.AxisService;
import org.apache.axis2.engine.ServiceLifeCycle;
public class Login implements ServiceLifeCycle{
static String IPprop = "";
static String rutaDB = "C:/resources/users_DB.txt";
static String rutaUddiXml = "C:/resources/uddi.xml";
static String rutaIP = "C:/resources/ip.txt";
static boolean registrado=false;
static String comp ="";
public static void main(String[] args) {
IP();
String nombreServicio = "Login";
String rutaServicio = "http://"+ IPprop +":8080/axis2/services/Login";
SimplePublishPortable spp = new SimplePublishPortable(rutaUddiXml);
spp.publish(nombreServicio, rutaServicio);
System.out.println("te registraste");
}
public static void createUser(String user, String pass) {
interacFich("crea", user, pass);
}
public static String loginAccess(String user, String pass) {
return interacFich("login", user, pass);
}
public static String runComprobation(){
return "deployed service" + comp;
}
public static String regComprobation(){
if(registrado==true){
return "registered";
}
else{
return "failed";
}
}
private static String getToken() {
String cadenaAleatoria = "";
int i = 0;
while (i < 10) {
char c = (char) ((int) (Math.random() * 255 + 1));
if ((c >= '0' && c <= '9') || (c >= 'A' && c <= 'Z')) {
cadenaAleatoria += c;
i++;
}
}
return cadenaAleatoria;
}
private static String interacFich(String accion, String user, String pass) {
String usuario = "";
LinkedHashMap<String, String> usuarios = new LinkedHashMap<String, String>();
File archivo = new File(rutaDB);
// leer fichero y meterlo en el mapa
if (archivo.exists() == false) {
try {
archivo.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
} else {
try (BufferedReader br = new BufferedReader(new FileReader(archivo))) {
while (br.ready()) {
usuario = br.readLine();
String[] param = usuario.split("\\*");
usuarios.put(param[0], param[1]);
}
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
switch (accion) {
case "crea":
usuarios.put(user + "-" + pass, getToken());
try (BufferedWriter bw = new BufferedWriter(new FileWriter(archivo))) {
Set<String> keysUsuarios = usuarios.keySet();
for (String k : keysUsuarios) {
bw.write(k + "*" + usuarios.get(k).toString());
bw.write("\n");
}
System.out.println("todo escrito");
bw.close();
return "el fichero se crea";
} catch (IOException e) {
e.printStackTrace();
}
break;
case "login":
if (usuarios.containsKey(user + "-" + pass)) {
return usuarios.get(user + "-" + pass);
}
return "User o pass erroneos";
default:
break;
}
return null;
}
private static void IP() {
File archivo = new File(rutaIP);
try (BufferedReader br = new BufferedReader(new FileReader(archivo))) {
br.readLine();
IPprop = br.readLine();
br.close();
} catch (IOException e) {
e.printStackTrace();
}
return;
}
#Override
public void startUp(ConfigurationContext arg0, AxisService arg1) {
///////////////
//registrarse//
///////////////
comp="entramos";
IP();
String nombreServicio = "Login";
String rutaServicio = "http://"+ IPprop +":8080/axis2/services/Login";
SimplePublishPortable spp = new SimplePublishPortable(rutaUddiXml);
spp.publish(nombreServicio, rutaServicio);
registrado=true;
}
#Override
public void shutDown(ConfigurationContext arg0, AxisService arg1) {
// TODO Auto-generated method stub
}
}
Have you created the Service Definition (services.xml) file, on which you describe your services?
I am referring to a file similar to the example in Code Listing 3: The Service Definition File in the following link (axis2 quick start):
https://axis.apache.org/axis2/java/core/docs/quickstartguide.html#services
I want to read string value by splitting | include white space from text file and store to Account class.This is my function for read text file.
public ArrayList<Account> loadAccount(String fn) throws IOException{
ArrayList<Account> account = new ArrayList<Account>();
Scanner infile = new Scanner(new InputStreamReader (new FileInputStream(fn)));
while(infile.hasNextLine()){
String accountNo = infile.nextLine();
String legencyNo = infile.nextLine();
Account c = new Account(accountNo, legencyNo);
account.add(c);
}
infile.close();
return account;
}
This is Account class.
public class Account {
private int id;
private String accountNo;
private String legencyNo;
}
This is AccountInformation.txt.
Account Number | Legacy Key | Description
80000001|7001111|
80000002| |
80000003|7001234|Testing
Update: This is my readFile class.Now, It's ok.I'm using StringUtils.
public static List<Account> readFile() {
String file = "C:\\Dev\\JBoss\\UpdateAccountNumber\\source\\AccountInformation.txt";
BufferedReader br = null;
String line = "";
String splitter = "\\|";
List<Account> accountList = new ArrayList<Account>();
try {
br = new BufferedReader(new FileReader(file));
while ((line = br.readLine()) != null) {
String[] accounts = org.apache.commons.lang3.StringUtils.split(line, splitter);
String accountNo = "",legencyNo="";
for(int i = 0;i<accounts.length;i++){
if (i == 0){
accountNo = (accounts[0] == null) ? "" : accounts[0];
}
if (i==1){
legencyNo = (accounts[1] == null) ? "" : accounts[1];
}
}
Account a = new Account(accountNo,legencyNo);
accountList.add(a);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (br != null) {
try {
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return accountList;
}
Just try as. Which mean split string include space .
String[] accounts = line.split(splitter, -1);
Fixed code:
Account class:
class Account
{
private int id;
private String accountNo;
private String legencyNo;
public Account(String accountNo, String legencyNo)
{
this.accountNo = accountNo;
this.legencyNo = legencyNo;
}
#Override
public String toString()
{
return this.accountNo + " " + this.legencyNo;
}
}
Test class:
public class Test
{
public static List<Account> readFile()
{
String file = "C:\\workspace\\practise\\test.txt";
BufferedReader br = null;
String line = "";
String splitter = "\\|";
List<Account> accountList = new ArrayList<Account>();
try
{
br = new BufferedReader(new FileReader(file));
while ((line = br.readLine()) != null)
{
Account a = null;
String[] accounts = line.split(splitter);
if (accounts.length > 1)
{
a = new Account(accounts[0], accounts[1]);
} else
{
a=new Account(accounts[0], "");
}
accountList.add(a);
}
} catch (Exception e)
{
e.printStackTrace();
} finally
{
if (br != null)
{
try
{
br.close();
} catch (IOException e)
{
e.printStackTrace();
}
}
}
return accountList;
}
public static void main(String[] args)
{
List<Account> acct = readFile();
for (Account account : acct)
{
System.out.println(account);
}
}
}
Test file:
Account Number|Legacy Key|Description
80000001|7001111|
80000002||
80000003|7001234|Testing
The problem in above code was that when you split in second record there is only one string present i.e 80000002, so you are trying to use accounts[1], but accounts length itself is 1 so you will have to handle with if clause on accounts.length. you can try above code its working. From next time i would suggest you to run your code in debug mode to check where you are getting exception.
If i understood your problem correctly, you need to change your loop
while(infile.hasNextLine()){
String line= infile.nextLine();
String[] tokens = line.split("\\|");
Account c = new Account(tokens[0], tokens[1]);
account.add(c);
}
There are two reasons for that,
First, your all data required are in single line 80000001|7001111|, so calling nextLine will bring you next row rather than data which you required
Second, it might cause you exception, as you are checking is next line exist, and ther you try to read two lines, which will obviousky fail if you have only one line
My goal is to read in a text file and add each element to a simple array (the elements are separated by a comma). The last method readData() is the one I can't figure out.
My code so far :
public class VersionChooser {
private Scanner scan;
private StockManager aManager = new StockManager("StockManager");
public VersionChooser() {
this.scan = new Scanner(System.in);
}
public void chooseVersion() {
this.readData();
this.runTextOption();
}
private void runTextOption() {
StockTUI tui = new StockTUI(this.aManager);
}
public StockManager readData() {
String fileName;
System.out.println("Enter the name of the file to be used");
fileName = this.scan.nextLine();
System.out.println(fileName);
try (final BufferedReader br = Files.newBufferedReader(new File("fileName").toPath(),
StandardCharsets.UTF_16)) {
for (String line; (line = br.readLine()) != null;) {
final String[] data = line.split(",");
StockRecord record = new StockRecord(data[0], Double.valueOf(data[4]));
this.aManager.getStockList().add(record);
}
} catch (IOException ioe) {
ioe.printStackTrace();
}
return null;
}
}
StockRecord :
public class StockRecord {
private String date;
private double closingPrice;
public StockRecord(String date, double closingPrice) {
this.date = date;
this.closingPrice = closingPrice;
}
public String getDate() {
return this.date;
}
public double getClosingPrice() {
return this.closingPrice;
}
public String toString() {
return "On " + this.date + " this stock had a closing price of $"
+ this.closingPrice;
}
}
Step1 : Read the file line by line.
Step2: Split the line by ","
Step3 : Construct the String[] to StockRecord.
try (final BufferedReader br = Files.newBufferedReader(new File("stock.txt").toPath(),
StandardCharsets.UTF_8)) {
List<StockRecord> stocks = new ArrayList<StockRecord>();
br.readLine() ; // to avoid first line
for (String line; (line = br.readLine()) != null;) { // first step
final String[] data = line.split(","); // second step
StockRecord record = new StockRecord(data[0], Double.valueOf(data[1]));
stocks.add(record); // third step
}
} catch (IOException e) {
e.printStackTrace();
}
Your stockRecord doesn't has all records. and for demo purpose i did assumed 2 element is closing price . change accordingly
I have a text file that has is set out like the following
Title - Welcome to the Dibb
Date - 13/03/11
Information - Hello and welcome to our website.
Title - Welcome to student room
Date - 06/05/11
Information - Hello and welcome to the student room. We are a online forum that allows previous and current students to ask questions.
I need to parse this text file and save things like the title line, date line and the rest will be saved as information. I know how to read the file and save the full file as a string but I am stuck on getting the select information.
CODE
This is the code I have used to read the text file
helloTxt.setText(readTxt());
}
private String readTxt() {
InputStream inputStream = getResources().openRawResource(R.raw.pages);
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
int i;
try {
i = inputStream.read();
while (i != -1) {
byteArrayOutputStream.write(i);
i = inputStream.read();
}
inputStream.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
String str = byteArrayOutputStream.toString();
return str;
}
Read file line by line
BufferedReader br = new BufferedReader(new FileReader(file));
String line;
while ((line = br.readLine()) != null) {
// process the line.
}
br.close();
If you can guarantee that every line has as maximum one - then you can use following pattern.
String[] tokens = line.split("\s-\s");
For this line
Title - Welcome to the Dibb
It would give you
tokens[0] = "Title";
tokens[1] = "Welcome to the Dibb";
I try to write some classes which can help you to approach your issue
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
public class Test4 {
private List<Information> parser(String data) {
List<Information> informations = new ArrayList<Information>();
String blocks[] = data.split("\n\r");
for(String block : blocks) {
String[] lines = block.split("\n");
Information information = new Information();
information.setTitle((lines[0].split("-"))[1].trim());
information.setDate((lines[1].split("-"))[1].trim());
information.setInfo((lines[2].split("-"))[1].trim());
informations.add(information);
}
return informations;
}
private void runner() throws IOException {
InputStream inputStream = getClass().getResourceAsStream("input.txt");
String input = "";
int cc;
while((cc = inputStream.read()) != -1) {
input += (char) cc;
}
List<Information> informations = parser(input);
for(Information information : informations) {
System.out.println(information);
}
}
/**
* #param args
* #throws IOException
*/
public static void main(String[] args) throws IOException {
Test4 test4 = new Test4();
test4.runner();
}
class Information {
private String title;
private String date;
private String info;
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getDate() {
return date;
}
public void setDate(String date) {
this.date = date;
}
public String getInfo() {
return info;
}
public void setInfo(String info) {
this.info = info;
}
#Override
public String toString() {
return "Information [" + (title != null ? "title=" + title + ", " : "")
+ (date != null ? "date=" + date + ", " : "") + (info != null ? "info=" + info : "") + "]";
}
}
}