How to store default constructor output in string? - java

public class demo2{
public demo2() throws FileNotFoundException {
Scanner scanner = new Scanner(new
File("/home/madhu/Desktop/demo.txt"));
while (scanner.hasNextLine())
System.out.println(scanner.nextLine());
}
public static void main(String[] args) throws FileNotFoundException {
demo2 obj = new demo2();
}
}
new demo2()
gives output as
Data1,200,1000
Data2,201,2000
How to store new demo2() value into String array or how to write to get output in such format ?
I want to store as
st1= Data1,200,1000
st2= Data2,201,2000

You could do something like this.
ScannerReader.class
public class ScannerReader {
private ArrayList<String> scannerInput;
public ScannerReader() {
scannerInput = new ArrayList<>();
readFileInput();
}
private void readFileInput() {
try {
Scanner scanner = new Scanner(new File("src\\date.txt"));
while (scanner.hasNextLine()) {
System.out.println(scanner.nextLine());
scannerInput.add(scanner.nextLine());
}
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
public void printArrayData() {
for(String line : scannerInput) {
System.out.println(line);
}
}
}
Main.class
public class Main {
public static void main(String[] args) {
ScannerReader reader = new ScannerReader();
reader.printArrayData();
}
}

Related

Change delimiter in OpenCSV CSVReader

I have the following piece of code which reads a CSV file.
public class TestMain {
public static void parseTsv(String filePath) throws Exception {
try (CSVReader reader = new CSVReader(new InputStreamReader(Objects.requireNonNull(TestMain.class.getResourceAsStream(filePath))))) {
String[] line;
while ((line = reader.readNext()) != null) {
System.out.println(line[0] + " " + line[1]);
}
}
}
public static void main(String[] args) {
try {
parseTsv("path-to-tsv-file");
} catch (Exception e) {
throw new RuntimeException(e);
}
}
}
And I want to modify the delimiter so that it can read tsv files (tab-separated). Any help would be greatly appreciated!
With g00se's help, please see below the correct code:
public class TestMain {
public static void parseTsv(String filePath) throws Exception {
try (CSVReader reader = new CSVReaderBuilder(new InputStreamReader(Objects.requireNonNull(TestMain.class.getResourceAsStream(filePath))))
.withCSVParser(new CSVParserBuilder().withSeparator('\t').build())
.build()) {
String[] line;
while ((line = reader.readNext()) != null) {
System.out.println(line[0] + " " + line[1]);
}
}
}
public static void main(String[] args) {
try {
parseTsv("path-to-tsv-file");
} catch (Exception e) {
throw new RuntimeException(e);
}
}
}

i can not write more than one object on a file in java

import java.io.*;
import java.util.ArrayList;
public class Main {
static ArrayList<test> testArrey = new ArrayList<test>();
public static void main(String[] args) {
output(new test(18, "aren"));
output(new test(22, "ahmad"));
input();
read();
}
public static void read() {
for (test a : testArrey) {
System.out.println(a.age);
}
}
public static void input() {
try {
FileInputStream fileInput = new FileInputStream("open.ses");
ObjectInputStream ObjectInput = new ObjectInputStream(fileInput);
Object a1 = ObjectInput.readObject();
test b1 = (test) a1;
testArrey.add(b1);
Object a2 = ObjectInput.readObject();
test b2 = (test) a2;
testArrey.add(b2);
ObjectInput.close();
} catch (Exception ex) {
System.out.println("input error");
ex.printStackTrace();
}
}
public static void output(test a) {
try {
FileOutputStream fileOut = new FileOutputStream("open.ses");
ObjectOutputStream objectOut = new ObjectOutputStream(fileOut);
objectOut.writeObject(a);
objectOut.close();
} catch (Exception ex) {
System.out.println("output error");
ex.printStackTrace();
}
}
public static class test implements Serializable {
int age ;
String name ;
public test(int age , String name ) {
this.age = age;
this.name = name;
}
}
}
as you can see a called output() method two time with new to object of (test)as argument ,and it must write two object on (open.ses)file but when i want to call (.readobject)two times it gives me an error that says one object is saved ............
how to write more than one object with the help of method like the one i wrote ??

calling method on other java application via lan

i have 2 java applications connected to each other via LAN (wifi network)
the first one ServerApp.java
public class ServerApp {
public static void zzz(){
System.out.println("hi");
}
public static void main(String[] args) {
try {
ServerSocket ss=new ServerSocket(6666);
Socket s=ss.accept();
DataInputStream dis = new DataInputStream(s.getInputStream());
String str =(String)dis.readUTF();
System.out.print("message : "+str);
ss.close();
} catch (IOException e) {
System.out.println(e);
}
}
}
the second one ClientApp.java
public class ClientApp {
public static void main(String[] args) {
try {
Scanner in = new Scanner(System.in);
System.out.print("send message to the server ?[y/n]:");
String inputString=in.next();
if ("y".equals(inputString)) {
Socket s= new Socket("192.168.20.125", 6666);
DataOutputStream dout=new DataOutputStream(s.getOutputStream());
dout.writeUTF("hellow server\n");
dout.writeUTF("zzz");
dout.flush();
dout.close();
s.close();
} else if ("n".equals(inputString)) {
System.out.println("exit");
} else {
System.out.println("error: you should enter a valid value");
}
} catch (IOException e) {
System.out.println(e);
}
}
}
what happens is, the client app send a message to the server app via LAN using the server IP address - the server app have a method call zzz() so all I want is how do I make the client app call this method ( if possible )
thanks
#MichalLonski how to I make the "obj" indicate to the ServerApp
As it is static method you have to point ServerApp.class, like below:
public class ServerApp {
public static void zzz() {
System.out.println("hi");
}
public static void main(String[] args) throws Exception {
String methodName = "zzz";
java.lang.reflect.Method method = ServerApp.class.getMethod(methodName);
method.invoke(ServerApp.class);
}
}
You can change it to use not static, but instance methods. In order to do that you have to create an instance of ServerApp class, like this:
public class ServerApp {
public void foo() {
System.out.println("Hello there from non static method!");
}
public static void main(String[] args) throws Exception {
String methodName = "foo";
ServerApp app = new ServerApp();
java.lang.reflect.Method method = app.getClass().getMethod(methodName);
method.invoke(app);
}
}
Edit:
If you want to specify also the class of which method you want to call, you can do it this way:
package com.example;
class Foo {
public static void bar() {
System.out.println("Hello there.");
}
}
public class ServerApp {
public static void main(String[] args) throws Exception {
//read the class and method name from the socket
String className = "com.example.Foo";
String methodName = "bar";
Class<?> clazz = Class.forName(className);
clazz.getMethod(methodName).invoke(clazz);
}
}

Console application with two threads

I just want to print learning... as long as I enter 1
package a;
import java.util.Scanner;
class main extends Thread {
static String n;
Scanner reader = new Scanner(System.in);
public void run() {
n = reader.nextLine();
}
public static void main(String args[]) throws InterruptedException {
(new Thread(new main())).start();
n="5";
System.out.println("1 = ON\n0 = OFF");
while (n.equals("1")) {
System.out.println("Learning..");
}
}
}
You may be interested in reading up on the Producer-Consumer pattern. You can take a look here http://javarevisited.blogspot.fr/2012/02/producer-consumer-design-pattern-with.html and try with something like
class main extends Thread {
// a thread-safe queue for decoupling reading and writing threads avoiding
// synchronization issues. The capacity of the queue is 1 to avoid reading (producing) a
// command without having handled (consumed) the previous before
private static final BlockingQueue<String> sharedQueue = new LinkedBlockingQueue<>(1);
Scanner reader = new Scanner(System.in);
public void run() {
while (true) {
String s = reader.nextLine();
try {
//if the queue is empty, adds the element,
//otherwise blocks waiting for the current element to be handled by main thread
sharedQueue.put(s);
} catch (InterruptedException e) {
e.printStackTrace();
Thread.currentThread().interrupt();
}
}
}
public static void main(String args[]) throws InterruptedException {
(new Thread(new main())).start();
System.out.println("1 = ON\n0 = OFF");
while (true) {
//will block till an element is available, then removes and handles it
final String s = sharedQueue.take();
if ("1".equals(s)) {
System.out.println("Learning..");
}
}
}
}
If you are trying to stop start, it is always better to maintain two threads one for printing and other for taking input. Try with blow code. It is working fine for me.
public class ThreadsStop {
static String n="";
class Printer extends Thread{
#Override
public void run() {
while(!n.equals(null)){
try {
Thread.sleep(1000);
if(n.trim().equals("1"))
System.out.println("Learning..");
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
class Starter extends Thread{
#Override
public void run() {
Scanner reader = new Scanner(System.in);
while(true){
System.out.println("1 = ON \n 0 = OFF");
n= reader.nextLine();
}
}
}
public static void main(String[] args) {
new ThreadsStop().start();
}
private void start() {
new Starter().start();
new Printer().start();
}
}
Use can use the given below code.
class main extends Thread {
static String n;
Scanner reader = new Scanner(System.in);
public void run() {
while (true) {
n = reader.nextLine();
if (Integer.parseInt(n) == 0) {
break;
}
}
}
public static void main(String args[]) throws InterruptedException {
(new Thread(new main())).start();
System.out.println("1 = ON\n0 = OFF");
while (n == null) {
}
while (n.equals("1")) {
System.out.println("Learning..");
}
System.out.println("DONE");
}
}
Try below program, it will take your input and print it.
class main extends Thread {
static String n;
Scanner reader = new Scanner(System.in);
public void run() {
System.out.println("Enter n value ");
n = reader.nextLine();
}
public static void main(String args[]) throws InterruptedException {
(new Thread(new main())).start();
n="5";
System.out.println("1 = ON\n0 = OFF");
while (n.equals("5")) {
//System.out.println("Learning..");
}
System.out.println(n);
}
}
The reason why your code is not taking input, before providing the input your main method executed, which means that program execution completed. I have done few modifications to your code. Now your code will take your input.

Declaring an array in java as an object?

I have recently been following some tutorials on how to program and whilst programming the public static void for an array, the tutorial said to declare the array as an object. Below is the code for the array and at the end of the code I have put a split between the two sections so it is visible to as where my question lies
import java.io.*;
import java.lang.*;
public class LoginList
{
int arraySize=500;
Login[] arrayLogin=new Login[arraySize];
int nextPosition=0;
int LoginLocation=-1;
public void addLogin(Login tempLoginParameters)
{
arrayLogin[nextPosition] = tempLoginParameters;
nextPosition++;
}
public void writeLogins()
{
try
{
BufferedWriter LoginWriter = new BufferedWriter(new FileWriter("LoginDetails.txt"));
for(int i=0;i<nextPosition;i++)
{
LoginWriter.write(arrayLogin[i].toString());
LoginWriter.newLine();
}
LoginWriter.close();
}
catch(Exception e)
{
System.out.println("Error with writer");
}
}
public void readLogins()
{
try
{
BufferedReader LoginReader = new BufferedReader(new FileReader("LoginDetails.txt"));
String ReadLine = LoginReader.readLine();
while(ReadLine!= null)
{
String[] arrayStringLogin = ReadLine.split(", ");
Login tempLogin = new Login();
tempLogin.UserName = arrayStringLogin[0];
tempLogin.Password = arrayStringLogin[1];
arrayLogin[nextPosition] = tempLogin;
nextPosition++;
ReadLine = LoginReader.readLine();
}
}
catch(Exception e)
{
System.out.println("Error with reader");
}
}
public void displayLoginDetails()
{
for(int i=0;i<nextPosition;i++)
{
System.out.println("Login "+nextPosition+": "+arrayLogin[i].toString());
}
}
public void searchLogins(String TempLog)
{
LoginLocation=-1;
for(int i=0;i<nextPosition;i++)
{
if(arrayLogin[i].UserName.equals(TempLog))
{
System.out.println("Match At Position:"+i);
LoginLocation=i;
}
else
{
System.out.println("No match for UserName");
}
}
}
public static void main(String[] args)
{
LoginList ll = new LoginList(); //Declares the array as an object
Why is it that you have to declare the array as an object? Look just above here.
Login tempLogin = new Login();
ll.readLogins();
ll.displayLoginDetails();
}
}
LoginList is not an array, it's a class that happens to have an array of Login objects as one of its instance members. The code in main creates an object of type LoginList and calls its methods; the LoginList object uses an array internally, but the main method doesn't have to know about it.

Categories