FileStreaming Saved File - java

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;
}

Related

JAVA Socket object + text

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) {
}
}
}

File Transfer between Client and Server using Sockets in Java

I am trying to build a client server model in java using sockets to share files.
It works fine for one iteration of loop for sending a file but after that no data is received on the server. Please take a look at my code and suggest me something to correct this.
FileClient.java
public class FileClient {
private void listFiles() {
try {
DataInputStream dis = new DataInputStream(s.getInputStream());
while (dis.available() > 0) {
System.out.println(dis.readUTF());
}
} catch (IOException ex) {
ex.printStackTrace();
}
}
private static void selectAndDownloadFiles() {
}
private Socket s;
public FileClient(String host, int port) {
try {
s = new Socket(host, port);
} catch (Exception e) {
e.printStackTrace();
}
}
public void sendFile(String file) throws IOException {
DataOutputStream dos = new DataOutputStream(s.getOutputStream());
FileInputStream fis = new FileInputStream(file);
File myFile = new File (file);
dos.writeUTF(file);
dos.writeInt((int)myFile.length());
try {
sleep(2);
} catch (InterruptedException ex) {
Logger.getLogger(FileClient.class.getName()).log(Level.SEVERE, null, ex);
}
byte[] buffer = new byte[8192];
while (fis.read(buffer) > 0) {
dos.write(buffer);
}
}
public static void main(String[] args) {
int choice = 0;
Scanner in = new Scanner(System.in);
FileClient fc = new FileClient("localhost", 1988);
DataOutputStream dos = null;
try {
dos = new DataOutputStream(fc.s.getOutputStream());
} catch (IOException ex) {
Logger.getLogger(FileClient.class.getName()).log(Level.SEVERE, null, ex);
}
do {
try {
System.out.println("Choose an action to perform..!");
System.out.println("1. List the files..");
System.out.println("2. Select and download files");
System.out.println("3. Send a file..");
System.out.println("0. Exit..");
choice = in.nextInt();
String fileName;
switch (choice) {
case 1:
try {
dos.write(choice);
System.out.println("List Files Request Sent..!");
} catch (IOException ex) {
Logger.getLogger(FileClient.class.getName()).log(Level.SEVERE, null, ex);
}
sleep(2);
fc.listFiles();
break;
case 2:
selectAndDownloadFiles();
break;
case 3:
try {
dos.write(choice);
} catch (IOException ex) {
Logger.getLogger(FileClient.class.getName()).log(Level.SEVERE, null, ex);
}
System.out.println("Enter file name to send");
fileName = in.next();
try {
fc.sendFile(fileName);
} catch (IOException ex) {
ex.printStackTrace();
}
break;
case 0:
System.exit(0);
break;
default:
System.out.println();
}
} catch (InterruptedException ex) {
Logger.getLogger(FileClient.class.getName()).log(Level.SEVERE, null, ex);
}
} while (choice != 0);
}
}
FileServer.java
public class FileServer extends Thread {
private static ServerSocket ss;
public FileServer(int port) {
try {
ss = new ServerSocket(port);
} catch (IOException e) {
e.printStackTrace();
}
}
public void run() {
File theDir = new File("C:\\Users\\Mehroz Irshad\\Desktop\\ServerFiles");
// if the directory does not exist, create it
if (!theDir.exists()) {
boolean result = false;
try {
theDir.mkdir();
result = true;
} catch (SecurityException se) {
//handle it
}
if (result) {
System.out.println("DIR created");
}
}
while (true) {
try {
Socket clientSock = ss.accept();
DataInputStream dis = new DataInputStream(clientSock.getInputStream());
DataOutputStream dos = new DataOutputStream(clientSock.getOutputStream());
int choice;
while ((choice = dis.read()) > 0) {
switch (choice) {
case 1:
System.out.println("List Files Request Received..!");
listFiles(clientSock);
System.out.println("List Files Response Sent..!");
break;
case 2:
sendSelectedFiles();
break;
case 3:
saveFile(clientSock);
break;
}
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
private void saveFile(Socket clientSock) throws IOException {
DataInputStream dis = new DataInputStream(clientSock.getInputStream());
String fileName = dis.readUTF();
int filesize = dis.readInt();
FileOutputStream fos = new FileOutputStream("C:\\Users\\Mehroz Irshad\\Desktop\\ServerFiles\\" + fileName);
try {
sleep(2);
} catch (InterruptedException ex) {
Logger.getLogger(FileServer.class.getName()).log(Level.SEVERE, null, ex);
}
byte[] buffer = new byte[8192];
// Send file size in separate msg
int read = 0;
int totalRead = 0;
int remaining = filesize;
while ((read = dis.read(buffer, 0, Math.min(buffer.length, remaining))) > 0) {
totalRead += read;
remaining -= read;
System.out.println("read " + totalRead + " bytes.");
fos.write(buffer, 0, read);
}
//fos.close();
//dis.close();
}
public static void main(String[] args) {
FileServer fs = new FileServer(1988);
fs.start();
}
private void listFiles(Socket clientSock) {
File folder = new File("C:\\Users\\Mehroz Irshad\\Desktop\\ServerFiles");
File[] listOfFiles = folder.listFiles();
try {
DataOutputStream dos = new DataOutputStream(clientSock.getOutputStream());
if (listOfFiles.length > 0) {
for (int i = 0; i < listOfFiles.length; i++) {
dos.writeUTF(listOfFiles[i].getName());
}
} else {
dos.writeUTF("There are no files on the server..!");
}
} catch (IOException ex) {
ex.printStackTrace();
}
}
private void sendSelectedFiles() {
}
}
Attached are the images of output.

BufferedWriter not printing

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

Refreshing a document

I have a writing/reading .txt files program, which I will put at the bottom so I can ask my question first: Usually, if I have the file open and run the program, I need to close the .txt file and reopen it in order to see the changes the program makes. Is there a way to refresh the document in the program so that It will change before my eyes in real time? Here is the program:
package SingleThings;
import java.io.*;
public class TextUtil {
public String path;
public String[] lines;
public TextUtil(String pathy,int length){
path=pathy;
makeFile();
lines = new String[length];
for(int i = 0;i<length;i++){
lines[i]=getLine(i+1);
}
}
public void clear(){
try{
FileWriter write = new FileWriter(path , false);
}catch(IOException e){
System.out.println("There was a problem oh noesss " + e);
}
}
private void makeFile(){
try {
File file = new File(path);
if (file.createNewFile()){
System.out.println("Creating file...");
}else{
System.out.println("Loading file...");
}
} catch (IOException e) {
e.printStackTrace();
}
}
public String getLine(int line){
BufferedReader in;
String read = null;
int linenum = line;
try {
in = new BufferedReader(new FileReader(path));
while(linenum > 0){
read = in.readLine();
linenum--;
}
in.close();
return read;
}catch(IOException e){
System.out.println("There was a problem:" + e);
return "error";
}
}
private void write(String text){
BufferedWriter out;
try {
out = new BufferedWriter(new FileWriter(path,true));
out.write(text);
out.newLine();
out.close();
}catch(IOException e){
System.out.println("There was a problem:" + e);
}
}
public void update(){
clear();
for(int i=0;i<lines.length;i++){
if(lines[i]!=null){
write(lines[i]);
}else{
write("");
}
}
}
}

Sending image Through TCP Socket in Java

I'm trying to make a Client Server Application which the server list name of available images and the client select one of them to download Such as here :
Thread in Server
public void run()
{
try {
in = new DataInputStream (server.getInputStream());
out = new DataOutputStream(server.getOutputStream());
out.writeUTF("To List images write list");
out.writeUTF("To Exit write 2");
out.flush();
while((line = in.readUTF()) != null && !line.equals("2")) {
if(line.equalsIgnoreCase("list"))
{
String [] images= processor.listImages();
for ( int i=0;i<images.length;i++) {
out.writeUTF((+1)+"-"+images[i]);
out.flush();
line = "";
}
out.writeUTF("-1");
line = in.readUTF();
if(line.equalsIgnoreCase("2"))
{
break;
}else
{
BufferedImage img =processor.processInput(line);
boolean cc = ImageIO.write(img,"JPG",server.getOutputStream());
if(!cc)
{
out.writeUTF("The entered image is not avaliable !");
}else
{
System.out.println("Image Sent");
}
}
}else if(line.equalsIgnoreCase("2")){
break;
}
}
try{
in.close();
out.close();
server.close();
}catch(Exception e){
System.out.println("Error : "+ e.getMessage());
}
} catch (IOException e) {
System.out.println("IOException on socket listen: " + e.getMessage());
}
}
Client :
public void start() throws IOException
{
String line="";
while(true)
{
try{
line = inputFromStream.readUTF();
System.out.println(line);
line = inputFromStream.readUTF();
System.out.println(line);
line = readFromConsol.readLine();
writeToStream.writeUTF(line);
if(line.equalsIgnoreCase("2")){
break;
}else if(line.equalsIgnoreCase("list")){
boolean check=true;
while(check){
line = inputFromStream.readUTF();
System.out.println(line);
if("-1".equals(line)) {
check=false;
}
}
line = readFromConsol.readLine();
if(line.equalsIgnoreCase("2")) {
break;
}else
{
writeToStream.writeUTF(line);
BufferedImage img=ImageIO.read(
ImageIO.createImageInputStream(client.getInputStream()));
File f = new File("E:/MyFile.png");
f.createNewFile();
ImageIO.write(img, "PNG", f);
//process.saveImage(tmp);
System.out.println("Saved");
}
}
}catch(Exception e)
{
System.out.println(e);
break;
}
}
try{
inputFromStream.close();
readFromConsol.close();
writeToStream.close();
this.client.close();
}catch(Exception e){
System.out.println("Error : "+e.getMessage());
}
}
The problem is that all commands are successfully submitted till image receiving image stop there doesn't move
Try doing a flush of the outstream on the sending socket, then close the socket.
The problem appears to be that until the socket is flushed and closed the receiving IOImage.read() will wait thinking there are more images in the stream.

Categories