I am trying to organise usernames and passwords into slots and assuming the username is not an email, I treat it as a password. I have to put these into files however it is not printing. It is reading though. Could I get some help? Thanks in advance.
public class Core {
public static void main(String[] args) {
FileReader in = null;
BufferedReader br = null;
BufferedWriter uOut = null;
BufferedWriter pOut = null;
try {
in = new FileReader("src/input.txt");
br = new BufferedReader(in);
uOut = new BufferedWriter(new FileWriter("src/username.txt"));
pOut = new BufferedWriter(new FileWriter("src/password.txt"));
String line = br.readLine();
while(line != null) {
boolean migrated = true;
if(line.contains(":")) {
String[] split = line.split(":");
String user = split[0];
String pass = split[1];
if(!(user.contains("#") && user.contains(".com"))) {
migrated = false;
}
if(migrated) {
uOut.write(user, 0, user.length());
uOut.newLine();
pOut.write(pass, 0, pass.length());
pOut.newLine();
} else {
pOut.write(user, 0, user.length());
pOut.newLine();
pOut.write(pass, 0, pass.length());
pOut.newLine();
}
line = br.readLine();
continue;
}
if(!(line.contains("#") && line.contains(".com"))) {
pOut.write(line, 0, line.length());
pOut.newLine();
line = br.readLine();
continue;
} else {
uOut.write(line, 0, line.length());
uOut.newLine();
line = br.readLine();
continue;
}
}
} catch(Exception ex) {
ex.printStackTrace();
} finally {
if(br != null) try { br.close(); } catch(Exception ex) { }
if(uOut != null) try { uOut.close(); } catch(Exception ex) { }
if(pOut != null) try { pOut.close(); } catch(Exception ex) { }
}
}
}
I should also mention that I do not get any exceptions and have no errors to show.
I tested your code with a file data.txt
foo:bar
blarg:bletch
blahonga:baar
Code with small changes
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileReader;
import java.io.FileWriter;
public class Main {
public static void main(String[] args) {
FileReader in = null;
BufferedReader br = null;
BufferedWriter uOut = null;
BufferedWriter pOut = null;
try {
in = new FileReader("data.txt");
br = new BufferedReader(in);
uOut = new BufferedWriter(new FileWriter("username.txt"));
pOut = new BufferedWriter(new FileWriter("password.txt"));
String line = br.readLine();
while (line != null) {
boolean migrated = true;
if (line.contains(":")) {
String[] split = line.split(":");
String user = split[0];
String pass = split[1];
if (user.contains("#") && user.contains(".com")) {
migrated = false;
}
if (migrated) {
uOut.write(user, 0, user.length());
uOut.newLine();
pOut.write(pass, 0, pass.length());
pOut.newLine();
} else {
pOut.write(user, 0, user.length());
pOut.newLine();
pOut.write(pass, 0, pass.length());
pOut.newLine();
}
line = br.readLine();
continue;
}
if (!(line.contains("#") && line.contains(".com"))) {
pOut.write(line, 0, line.length());
pOut.newLine();
line = br.readLine();
continue;
} else {
uOut.write(line, 0, line.length());
uOut.newLine();
line = br.readLine();
continue;
}
}
} catch (Exception ex) {
ex.printStackTrace();
} finally {
if (br != null) try {
br.close();
} catch (Exception ex) {
}
if (uOut != null) try {
uOut.close();
} catch (Exception ex) {
}
if (pOut != null) try {
pOut.close();
} catch (Exception ex) {
}
}
}
}
The result is 2 files:
username.txt
foo
blarg
blahonga
password.txt
bar
bletch
baar
Related
Does it possible, to get from client and
objetObjectInputStream
and
in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
for example, some client send me tet message, and someone send files. Should I make a new socket server for each?
public class ServerRequests {
Connection con = new Connection();
private Socket socket;
private BufferedReader in;
private BufferedWriter out;
public ServerRequests(Socket socket) throws IOException {
this.socket = socket;
in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
out = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
run();
}
public void run() {
String word;
try {
String object;
ObjectInputStream obIn = new ObjectInputStream(socket.getInputStream());
while ((object = (String) obIn.readObject()) != null){
if (object.contains("F47S")){
String[] result = object.split(":");
String fileName = result[1];
String url = result[2];
String culture = result[3];
System.out.println("FileName:" +fileName);
System.out.println("url:" +url);
FileOutputStream outOb = null;
if(culture.contains("test")) {
outOb = new FileOutputStream(fileName);
}
DataInputStream inOb = new DataInputStream(socket.getInputStream());
byte[] bytes = new byte[5*1024];
int count, total=0;
long lenght = inOb.readLong();
while ((count = inOb.read(bytes)) > -1) {
total+=count;
outOb.write(bytes, 0, count);
if (total==lenght) break;
}
outOb.close();
}
}
}catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
// while (true) {
word = in.readLine();
System.out.println(word);
if (word != null) {
String[] result = word.split(":");
String type = result[0];
if (type.contains("AUTH")) {
String login = result[2];
String pass = result[4];
String gui = con.checkLogin(pass, login);
auth(gui);
}
} catch (IOException e) {
}
}
private void auth(String gui) {
try {
out.write(gui + "\n");
out.flush();
} catch (IOException ignored) {
}
}
private void success(String status) {
try {
out.write(status+ "\n");
out.flush();
} catch (IOException ignored) {
}
}
}
I have written a multi-client TCP server that has the dual purpose of sending Json (text based) command strings and also sending an SQLite database file to multiple clients. Everything is working nicely except... the database file uses the special character hex81 (decimal 129) for some internal purpose. When I read the database file into a byte array, Java converts this character to decimal -127 because of Java's signed representation of bytes. However the socket is actually transmitting this character as hex3F. So when I receive the save the data in the client and save it to a file, the database is corrupt due to the presence of h3F chars instead of h81.
Why is this happening and how do I correct it?
Here is the complete code that I am using for the server (a new instance of this class is started by a separate TCPServer class whenever a client connects):
public class TCPServerThread extends Thread {
// Connect status constants
private final static int NULL = 0;
private final static int DISCONNECTED = 1;
private final static int DISCONNECTING = 2;
private final static int BEGIN_CONNECT = 3;
private final static int CONNECTED = 4;
private final static String END_SESSION = new Character((char)0).toString(); // Indicates the end of a session
// Connection state info
private int connectionStatus = DISCONNECTED;
private static StringBuffer txBuffer = new StringBuffer("");
private static ByteArrayOutputStream txBuffer2 = new ByteArrayOutputStream();
private static File file;
// TCP Components
private ServerSocket serverSocket = null;
private Socket clientSocket = null;
private BufferedReader in = null;
private PrintWriter out = null;
private DataOutputStream out2 = null;
private String s = "";
private DecodeJson dj = new DecodeJson();
private boolean doRun;
public TCPServerThread(Socket socket) throws IOException {
doRun = true;
clientSocket = socket;
changeStatusTS(BEGIN_CONNECT, true);
}
public void run() {
while (doRun) {
try { // run every ~10 ms
Thread.sleep(10);
}
catch (InterruptedException e) {}
if (Mainscreen.shutdown == true || TCPClient.close == true)
connectionStatus = DISCONNECTING;
switch (connectionStatus) {
case BEGIN_CONNECT:
try {
in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
out = new PrintWriter(clientSocket.getOutputStream(), true);
out2 = new DataOutputStream(clientSocket.getOutputStream());
TCPServer.writers.add(out); // add this socket to the connected clients list
changeStatusTS(CONNECTED, true);
}
// If error, clean up and output an error message
catch (IOException e) {
cleanUp();
changeStatusTS(DISCONNECTED, false);
}
break;
case CONNECTED:
try {
// Send data
if (txBuffer.length() != 0) {
for (PrintWriter writer : TCPServer.writers) {
writer.print(txBuffer);
writer.flush();
if(writer.checkError()) {
closeSocket();
changeStatusTS(DISCONNECTING, true);
}else {
changeStatusTS(NULL, true);
}
}
txBuffer.setLength(0);
}
if (txBuffer2.size() != 0) {
byte[] result = txBuffer2.toByteArray();
System.out.println(result[745] + "," + result[746] + "," + result[747] + "," + result[748] + "," + result[749] + "," + result[750]);
out2.write(result);
out2.flush();
txBuffer2.reset();
}
// Receive data
if (in.ready()) {
s = in.readLine();
if ((s != null) && (s.length() != 0)) {
// Check if it is the end of a transmission
if (s.equals(END_SESSION)) {
changeStatusTS(DISCONNECTING, true);
}
// Otherwise, receive text
else {
dj.receiveString(s);
changeStatusTS(NULL, true);
}
}
}
}
catch (IOException e) {
System.out.println("Socket error " + e);
cleanUp();
changeStatusTS(DISCONNECTED, false);
}
break;
case DISCONNECTING:
// Tell clients to disconnect as well
if (out != null) {
out.print(END_SESSION);
out.flush();
}
// Clean up (close all streams/sockets)
cleanUp();
changeStatusTS(DISCONNECTED, true);
break;
default: break;
}
}
}
// Add command to text send-buffer
public static void sendString(String s) {
synchronized (txBuffer) {
txBuffer.append(s + "\n");
}
}
// Add file data to binary send buffer
public static void sendFile(String filename) {
synchronized (txBuffer2) {
file = new File(filename);
byte[] content = new byte[(int)file.length()];
FileInputStream fin;
try {
fin = new FileInputStream(file);
fin.read(content);
System.out.println(content[745] + "," + content[746] + "," +content[747] + "," +content[748] + "," + content[749] + "," + content[750]);
txBuffer2.write(content);
fin.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException f) {
f.printStackTrace();
}
}
}
private void changeStatusTS(int newConnectStatus, boolean noError) {
// Change state if valid state
if (newConnectStatus != NULL) {
connectionStatus = newConnectStatus;
}
}
private void closeSocket(){
try {
if (clientSocket != null) {
clientSocket.close();
clientSocket = null;
}
}
catch (IOException e) { clientSocket = null; }
}
// Cleanup for disconnect
private void cleanUp() {
try {
if (serverSocket != null) {
serverSocket.close();
serverSocket = null;
}
}
catch (IOException e) { serverSocket = null; }
try {
if (clientSocket != null) {
clientSocket.close();
clientSocket = null;
}
}
catch (IOException e) { clientSocket = null; }
try {
if (in != null) {
in.close();
in = null;
}
}
catch (IOException e) { in = null; }
if (out != null) {
TCPServer.writers.remove(out); // remove this socket for the connected sockets list
out.close();
out = null;
}
doRun = false;
}
}
So as EJP suggested, the problem is due to using readers and writers.
The following code now works as expected (thanks for the tip EJP). I will get around to addressing the issue raised by VGR about wrapping client.getOutputStream() in both a PrintWriter and a BufferedOutputStream, but for now the code works nicely (this is a work in progress).
public class TCPServerThread extends Thread {
// Connect status constants
private final static int NULL = 0;
private final static int DISCONNECTED = 1;
private final static int DISCONNECTING = 2;
private final static int BEGIN_CONNECT = 3;
private final static int CONNECTED = 4;
private final static String END_SESSION = new Character((char)0).toString(); // Indicates the end of a session
// Connection state info
private int connectionStatus = DISCONNECTED;
private static StringBuffer txBuffer = new StringBuffer("");
private static BufferedOutputStream out2 = null;
private static File file;
// TCP Components
private ServerSocket serverSocket = null;
private Socket clientSocket = null;
private BufferedReader in = null;
private PrintWriter out = null;
private static BufferedInputStream fileData = null;
private String s = "";
private DecodeJson dj = new DecodeJson();
private boolean doRun;
public TCPServerThread(Socket socket) throws IOException {
doRun = true;
clientSocket = socket;
changeStatusTS(BEGIN_CONNECT, true);
}
public void run() {
while (doRun) {
try { // run every ~10 ms
Thread.sleep(10);
}
catch (InterruptedException e) {}
if (Mainscreen.shutdown == true || TCPClient.close == true)
connectionStatus = DISCONNECTING;
switch (connectionStatus) {
case BEGIN_CONNECT:
try {
in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
out = new PrintWriter(clientSocket.getOutputStream(), true);
out2 = new BufferedOutputStream(clientSocket.getOutputStream());
TCPServer.writers.add(out); // add this socket to the connected clients list
changeStatusTS(CONNECTED, true);
}
// If error, clean up and output an error message
catch (IOException e) {
cleanUp();
changeStatusTS(DISCONNECTED, false);
}
break;
case CONNECTED:
try {
// Send data
if (txBuffer.length() != 0) {
for (PrintWriter writer : TCPServer.writers) {
writer.print(txBuffer);
writer.flush();
if(writer.checkError()) {
closeSocket();
changeStatusTS(DISCONNECTING, true);
}else {
changeStatusTS(NULL, true);
}
}
txBuffer.setLength(0);
}
if (fileData != null) {
byte[] buffer = new byte[(int) file.length()];
for (int read = fileData.read(buffer); read >=0; read = fileData.read(buffer)) out2.write(buffer, 0, read);
out2.flush();
fileData = null;
}
// Receive data
if (in.ready()) {
s = in.readLine();
if ((s != null) && (s.length() != 0)) {
// Check if it is the end of a transmission
if (s.equals(END_SESSION)) {
changeStatusTS(DISCONNECTING, true);
}
// Otherwise, receive text
else {
dj.receiveString(s);
changeStatusTS(NULL, true);
}
}
}
}
catch (IOException e) {
System.out.println("Socket error " + e);
cleanUp();
changeStatusTS(DISCONNECTED, false);
}
break;
case DISCONNECTING:
// Tell clients to disconnect as well
if (out != null) {
out.print(END_SESSION);
out.flush();
}
// Clean up (close all streams/sockets)
cleanUp();
changeStatusTS(DISCONNECTED, true);
break;
default: break;
}
}
}
// Add command to text send-buffer
public static void sendString(String s) {
synchronized (txBuffer) {
txBuffer.append(s + "\n");
}
}
// Add file data to binary send buffer
public static void sendFile(String filename) {
file = new File(filename);
try {
fileData = new BufferedInputStream(new FileInputStream(file));
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
private void changeStatusTS(int newConnectStatus, boolean noError) {
// Change state if valid state
if (newConnectStatus != NULL) {
connectionStatus = newConnectStatus;
}
}
private void closeSocket(){
try {
if (clientSocket != null) {
clientSocket.close();
clientSocket = null;
}
}
catch (IOException e) { clientSocket = null; }
}
// Cleanup for disconnect
private void cleanUp() {
try {
if (serverSocket != null) {
serverSocket.close();
serverSocket = null;
}
}
catch (IOException e) { serverSocket = null; }
try {
if (clientSocket != null) {
clientSocket.close();
clientSocket = null;
}
}
catch (IOException e) { clientSocket = null; }
try {
if (in != null) {
in.close();
in = null;
}
}
catch (IOException e) { in = null; }
if (out != null) {
TCPServer.writers.remove(out); // remove this socket for the connected sockets list
out.close();
out = null;
}
doRun = false;
}
}
I am stuck on how to be able to load a CSV that
Try this
public class FileParser {
public static ArrayList<String> parseFile(String fileName){
String csvFile = fileName;
BufferedReader br = null;
String line = "";
final String DELIMITER = ",";
ArrayList<String> data = new ArrayList<String>();
try {
int counter = 0;
int N = 10;
br = new BufferedReader(new FileReader(csvFile));
while ((line = br.readLine()) != null && counter < N) {
if(counter >= 0){
String dataRow = line;
data.add(dataRow);
}
counter++;
}
for (String string : data) {
string.split(DELIMITER);
System.out.println(string);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (br != null) {
try {
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return data;
}
}
What you can do is :
Skip the first row if it has X Y Z.
Declare two more ArrayList to store Y and Z column.
You can do it like this :
public class FileParser {
public ArrayList<String> parseFile(String fileName){
String csvFile = fileName;
BufferedReader br = null;
String line = "";
final String DELIMITER = ",";
ArrayList<String> dataX = new ArrayList<String>();
ArrayList<String> dataY = new ArrayList<String>();
ArrayList<String> dataZ = new ArrayList<String>();
try {
int counter = 0;
int N = 10;
br = new BufferedReader(new FileReader(csvFile));
while ((line = br.readLine()) != null && counter < N) {
if(counter > 0){
String[] dataRow = line.split(DELIMITER);
dataX.add(dataRow[0]);
dataY.add(dataRow[1]);
dataZ.add(dataRow[2]);
}
counter++;
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (br != null) {
try {
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return data;
}
I guess better option would be to create a custom class with three variables x,y and z. Then use this class object to store data. Make implementation changes to overrided equals and hashCode methods as required.
public final class CsvData{
private String x;
private String y;
private String z;
public CsvData(String x, String y, String z){
this.x = x;
this.y = y;
this.z = z;
}
//getters and setters
public boolean equals(Object o) {
if (o instanceof CsvData) {
CsvData node = (CsvData)o;
return (x.equals(node.x) && y.equals(node.y) && z.equals(node.z));
}
return false;
}
public int hashCode() {
return HashCodeBuilder.reflectionHashCode(this);
}
}
public class FileParser {
public ArrayList<CsvData> parseFile(String fileName){
String csvFile = fileName;
BufferedReader br = null;
String line = "";
final String DELIMITER = ",";
ArrayList<CsvData> data = new ArrayList<CsvData>();
try {
int counter = 0;
int N = 10;
br = new BufferedReader(new FileReader(csvFile));
while ((line = br.readLine()) != null && counter < N) {
String[] dataRow = line.split(DELIMITER);
CsvData csvData = new CsvData(dataRow[0],dataRow[1],dataRow[2]);
data.add(csvData);
counter++;
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (br != null) {
try {
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return data;
}
public static void main(String[] args) {
String filePath = "C:/Program Files/ZBar/bin/zbarimg -d C:/Program Files/ZBar/examples/barcode.png";
try {
System.out.println("hello");
Process p = Runtime.getRuntime().exec(filePath);
//BufferedReader in = new BufferedReader(new InputStreamReader(p.getInputStream()));
System.out.println("World");
final InputStream stdout = p.getInputStream();
final OutputStream stdin = p.getOutputStream();
new Thread(new Runnable() {
#Override
public void run() {
String line;
BufferedReader br = new BufferedReader(new InputStreamReader(stdout));
try {
while ((line = br.readLine()) != null) {
System.out.println("[OUT] " + line);
}
} catch (IOException e) {
e.printStackTrace();
}
}
}).start();
new Thread(new Runnable() {
public void run() {
try {
byte[] buffer = new byte[1024];
int bytesRead;
while ((bytesRead = System.in.read(buffer)) != -1) {
for(int i = 0; i < buffer.length; i++) {
int intValue = new Byte(buffer[i]).intValue();
if (intValue == 0) {
bytesRead = i;
break;
}
}
// for some reason there are 2 extra bytes on the end
stdin.write(buffer, 0, bytesRead-2);
System.out.println("[IN] " + new String(buffer, 0, bytesRead-2) + " [/IN]");
}
} catch (IOException e) {
e.printStackTrace();
}
}
}).start();
} catch (Exception e) {
e.printStackTrace();
}
}
}
You probably shouldn't be invoking an external process to decode like that, I suspect you're receiving a '\r\n' (aka Carraige Return Line Feed) from your external process. I recommend you use a Java library to perform the decode... here is how you might with ZXing "Zebra Crossing".
This section of the code is not working. I'm trying to display the name saved in the file when the user has clicked n==1 into the textfield when the user has clicked n==0. It comes out blank for some reason I can't figure. Maybe I'm not calling the savedName return value properly?
if (n == 1){
for(fn=JOptionPane.showInputDialog("What is your first name?");!fn.matches("[a-zA-Z]+");fn.isEmpty()){
JOptionPane.showMessageDialog(null, "Alphabet characters only.");
fn=JOptionPane.showInputDialog("What is your first name?");
}
writeToFile();
for(sn=JOptionPane.showInputDialog("What is your second name?");!sn.matches("[a-zA-Z]+");sn.isEmpty()){
JOptionPane.showMessageDialog(null, "Alphabet characters only.");
sn=JOptionPane.showInputDialog("What is your second name?");
}
if (n == 0){
String fullName = readFromFile();
text.setText("Welcome " + fullName + ".");
System.out.println(fullName);
}
}
private void writeToFile() {
String nameToWrite = fn;
OutputStream outStream = null;
//String savedName = "";
try {
outStream = new FileOutputStream(f);
outStream.write(nameToWrite.getBytes());
//BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(f)));
//savedName = br.readLine();
text.setText("Welcome " + fn + ".");
//System.out.println(savedName);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
if (null != outStream) {
try {
outStream.close();
} catch (IOException e) {
// do nothing
}
}
}
//return savedName;
}
private String readFromFile(){
String savedName="";
try {
BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(f)));
savedName = br.readLine();
} catch (IOException e) {
e.printStackTrace();
}
return savedName;
}