Scanner to byte[]? - java

I have to copy txt file to RAM(use ByteArrayOutputStream), next to make a list with all of the words and number of repeats.
But when I try print that list, it print me
"java.util.Scanner[delimiters=\p{javaWhitespace}+][position=0][match
valid=false][need input=false][source
closed=false][skipped=false][group separator=\ ][decimal
separator=\,][positive prefix=][negative prefix=\Q-\E][positive
suffix=][negative suffix=][NaN string=\Q?\E][infinity string=\Q?\E]
I found here where is the problem(That Scanner is not a String Object)but can't find a solution.
Could u check my code and help?
{
public class JavaRam {
File f;
byte [] bTab;
Scanner sc;
String tempLine;
ByteArrayOutputStream baos;
StringTokenizer st;
long startTime=0;
long stopTime=0;
HashMap<String,Integer> hm;
JavaRam(String fileName) throws IOException{
startTime=System.currentTimeMillis();
loadFile(fileName); //load file to ram
System.out.println("Czas ladowania pliku: "+ (stopTime=System.currentTimeMillis()-startTime));
startTime=System.currentTimeMillis();
hm=new HashMap<String, Integer>();
makeList();
System.out.println("Czas tworzenia listy wyrazow: "+ (stopTime=System.currentTimeMillis()-startTime));
startTime=System.currentTimeMillis();
printing();
System.out.println("Czas drukowania listy wyrazow: "+ (stopTime=System.currentTimeMillis()-startTime));
exit();
System.exit(0);
}
void loadFile(String fileName){
try{
f=new File(fileName+".txt");
sc=new Scanner(f);
}
catch(Exception e){
e.printStackTrace();
}
tempLine=new String(sc.toString());
bTab=tempLine.getBytes();
baos=new ByteArrayOutputStream();
try{
baos.write(bTab);
}
catch(Exception e){
e.printStackTrace();
}
}
void makeList(){
st=new StringTokenizer(baos.toString());
Integer ti; //temporary int
for(String nt=st.nextToken(); st.hasMoreTokens()==true;nt=st.nextToken()){
if(hm.containsKey(nt)==false){
hm.put(nt, 1);
}
else{
hm.put(nt,(Integer)hm.get(nt)+1);
}
}
}
void printing(){
String sl="Slowo";
String lp="Liczba powtorzen:";
String sl1="";
String lp1="";
for(String str:hm.keySet()){
sl1=sl+str;
lp1=lp+hm.get(str).toString();
System.out.printf("\n %-20s, %-20s",sl1,lp1);
}
}
int exit() throws IOException{
baos.close();
sc.close();
return 1;
}
public static void main(String []args){
try {
JavaRam a=new JavaRam("JPJMMWKM");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
Thanks in advance ;)

tempLine=new String(sc.toString()); that seems wrong; you probably wants sc.nextLine().
Anyway, your code is really confusing. The code in the constructor should be go into another method, too much instance members, etc, etc.

Related

How to handle ZipException(Wrong password for file : Demo.zip) and display appropriate messages

Since I'm new to Java, I have created a method to unzip password protected zip files, I have used zip4j library for unzipping the zip file,the code works fine when the password is correct, but when the password is wrong how to handle the ZipException(net.lingala.zip4j.exception.ZipException: net.lingala.zip4j.exception.ZipException: net.lingala.zip4j.exception.ZipException: Wrong Password for file: Demo.zip)and display appropriate message(Wrong Password!).Please Help, Here is my code.
import net.lingala.zip4j.core.ZipFile;
import net.lingala.zip4j.exception.ZipException;
import net.lingala.zip4j.model.ZipParameters;
import net.lingala.zip4j.util.Zip4jConstants;
public class UnunzipDemo{
public void unzipFilesWithPassword(String sourceZipFilePath,String extractedZipFilePath,String password){
try {
ZipFile zipFile = new ZipFile(sourceZipFilePath);
if (zipFile.isEncrypted()) {
zipFile.setPassword(password);
}
zipFile.extractAll(extractedZipFilePath);
System.out.println("Done");
}
catch (ZipException e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
String sourceZipFilePath="E:/MyFiles/Files/Zip/Demo.zip";
String extractedZipFilePath="E:/MyFiles/Files/Unzip/";
String password="JOEL"; //Correct Password
UnunzipDemo unzipDemo=new UnunzipDemo();
unzipDemo.unzipFilesWithPassword(sourceZipFilePath,extractedZipFilePath,password);
}
}
Maybe you can read the password from console.
For instance:
private static String password = "123";
public static void main(String[] args) {
// read the input password from console
// if you have UI, maybe you can read it from some way.
Scanner sc = new Scanner(System.in);
String inputPassword = sc.next();
while (true) {
//do something...
try {
unzip(inputPassword);
break;
} catch (Exception e) {
inputPassword = sc.next();
}
}
}
private static void unzip(String inputPassword) {
if (inputPassword.equals(password)) {
//unzip
} else {
// just demo. In your case, this is ZipException
throw new IllegalArgumentException("wrong password");
}
}
You can also check the error code.
public void unzipFilesWithPassword(String sourceZipFilePath,String extractedZipFilePath,String password){
try {
ZipFile zipFile = new ZipFile(sourceZipFilePath);
if (zipFile.isEncrypted()) {
zipFile.setPassword(password);
}
zipFile.extractAll(extractedZipFilePath);
System.out.println("Done");
}
catch (ZipException e) {
if (e.getCode == ZipExceptionConstants.WRONG_PASSWORD) {
// Handle wrong password scenario
System.out.println("Wrong password");
} else {
//Handle other exception scenario - printing out error messages?
}
}

Exception in thread "main" java.util.NoSuchElementExceptionat java.util.Scanner.throwFor(Scanner.java:907)

I know this question has been asked before, but I've tried the solution scannername.hasNextInt() and it still doesn't work. Under CalculateGPA the error is thrown after the line "enter marks for subject1". RegisterStudent only takes in subject names and their credits.
class CalculateGPA {
RegisterStudent s;
int scoreSum=0;
CalculateGPA(RegisterStudent std){
s=std;
System.out.println("\nIn calculate\n");
}
void findGPA() throws NumberFormatException,InvalidGPAException {
Scanner sc =new Scanner(System.in);
int marks1,marks2,marks3;
String result;
System.out.println("\nEnter the marks for "+s.subject1);
if(sc.hasNext()){
marks1=sc.nextInt();
result=findGrade(marks1);
System.out.println(s.subject1+" "+result);
}
}
My main class:
public class all {
public static void main(String args[]){
RegisterStudent s1=new RegisterStudent();
//RegisterStudent s2=new RegisterStudent();
s1.getBranch("ISE");
s1.getName("Saniya");
try{
s1.register();
}
catch(CreditLimitException e){
System.out.println(e);
}
CalculateGPA cal=new CalculateGPA(s1);
try{
cal.findGPA();
}
catch(NumberFormatException e){
System.out.println(e);
}
catch(InvalidGPAException e){
System.out.println(e);
}
}
}

Reading numbers from a .txt file in java and adding them

I have a text file with some account holders and numbers of books they have on loan. I need to read the file, add how many account there are and add the total number of books.
These are the account holders and the total number of books.
Tim Newton 14
Leon Jones 21
Bill Bob 94
Sarah Gooding 67
{
private int count;
private File inFile, outFile;
private Scanner input;
private String name;
private PrintWriter output;
private int total;
public test(String name, String id, String inFileName, String outFileName) {
inFile = new File(inFileName);
if (!inFile.exists()) {
throw new IllegalStateException(inFileName + " does not exist");
}
outFile = new File(outFileName);
}
public void makeLink() throws FileNotFoundException {
input = new Scanner(inFile);
output = new PrintWriter(outFile);
}
public void processFiles() {
try {
while (input.hasNext()) {
String line = input.nextLine();
output.println(line);
}
} catch (NullPointerException e) {
System.out.println(" Scanner not assigned");
}
}
public void closeLink() {
try {
input.close();
} catch (NullPointerException e) {
System.out.println(" Scanner not assigned");
}
try {
output.close();
} catch (NullPointerException e) {
System.out.println(" PrintWriter not assigned");
}
}
}
Here is the edited code with the scanner answer implemented:
public void makeLink() throws FileNotFoundException {
input = new Scanner(inFile);
output = new PrintWriter(outFile);
numbers = new Scanner(inFile)
}
public void processFiles() {
try {
// your current code then
while (account.hasNextInt()) {
String line = input.nextLine()
while (numbers.hasNextInt()) {
total += numbers.nextInt();
}
output.println(line);
}
} catch (NullPointerException e) {
System.out.println(" Scanner not assigned");
}
}
enter code here
Use scanner.hasNextInt() and scanner.nextInt()
You may want to have another scanner that looks for numbers in the file:
private Scanner account; // initialise this in makeLink
public void processFiles() {
try {
// your current code then
while (account.hasNextInt()) {
total += account.nextInt();
}
} catch (NullPointerException e) {
System.out.println(" Scanner not assigned");
}
}
Note: It is worthwhile to read the java API.

binary search from a file

how can I search a data using binary search? When if statement begins, the program goes to IOException block. It seems that it doesn't try to read the file.
public void busquedaDicotomica1(String clave)
{
String lectura1=null, lectura2=null ;
long posicion;
long tamaño;
long midValue;
boolean valido = true;
try
{
rafObj = new RandomAccessFile("indice1.ind","r");
tamaño = rafObj.length();
midValue = tamaño/2;
rafObj.seek(midValue);
if(clave.equalsIgnoreCase(rafObj.readUTF()))
{
System.out.println("ok");
}
else
{
System.out.println("no");
}
}
catch(EOFException eoe)
{}
catch(FileNotFoundException nfe)
{
VentanaPrincipal.setErrorText(dialogo);
}
catch(IOException ioe)
{
VentanaPrincipal.setErrorText(ioe.getMessage());
}
}
}

Com port InputStream

I am sending a text message to mobile number. I write the data using a o/p stream and read the data using i/p stream from Port. The o/p stream is working properly, but I can not read the data from the i/p stream. Here is my code:
public class SendMsg implements SerialPortEventListener
{
Enumeration portList;
CommPortIdentifier portId;
SerialPort serialPort;
OutputStream outputStream;
InputStream inputStream;
Thread readThread;
String messageString;
String messageString1;
String strResponse="";
SendMsg pWriter;
String msg[]=new String[200];
int ix=0;
boolean msgEnd=true;
String className;
static Enumeration ports;
static CommPortIdentifier pID;
static String messageToSend = "ComPortSendMsg deatails!\n";
public SendMsg(String className) throws NoSuchPortException, IOException
{
this.className=className;
ports = CommPortIdentifier.getPortIdentifiers();
System.out.println("ports name"+ports);
while(ports.hasMoreElements())
{
pID = (CommPortIdentifier)ports.nextElement();
System.out.println("Port Name " + pID.getName());
if (pID.getPortType() == CommPortIdentifier.PORT_SERIAL)
{
System.out.println("Port Name 1 " + pID.getName());
if (pID.getName().equals("COM1"))
{
try {
System.out.println("Port Name 2 " + pID.getName());
System.out.println("COM1 found");
serialPort=(SerialPort)pID.open(className, 9600);
outputStream=serialPort.getOutputStream();
inputStream=serialPort.getInputStream();
break;
} catch (PortInUseException ex) {
Logger.getLogger(SendMsg.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
}
}
public void closePort()
{
try
{
inputStream.close();
System.out.println("Finished2");
outputStream.close();
System.out.println("Finished1");
serialPort.close();
System.out.println("Finished");
}
catch(Exception e)
{
System.out.println("Close Error"+e);
}
}
public void send(String phno,String msg)
{
String s = "AT+CMGF="+1;
System.out.println("AT+CMGF command :"+s);
messageString = "AT+CMGS=\""+phno+"\"\r";
messageString1 = msg+"\n" +(char)26;
System.out.println("AT CMGS "+messageString);
System.out.println("AT CMGS "+messageString1);
try
{
outputStream.write(s.getBytes());
System.out.print("this is send try block");
outputStream.write(messageString.getBytes());
outputStream.write(messageString1.getBytes());
Thread.sleep(2000);
byte[] b = new byte[1000];
String r="";
String r1="";
System.out.println(inputStream.available());
while (inputStream.available() > 0) {
int n = inputStream.read(b);
System.out.println("number of bytes"+n);
r= new String(b);
}
System.out.println("this is input stream msg"+r);
}
catch (Exception e)
{
System.out.println(e);
}
}
public static void main(String args[]) throws NoSuchPortException, IOException
{
SendMsg f=new SendMsg("Msg Sending");
f.send("9884345649","Wish U Happy");
System.out.println("---------END--------");
f.closePort();
}
#Override
public void serialEvent(SerialPortEvent spe) {
throw new UnsupportedOperationException("Not supported yet.");
}
}
You should be reading the InputStream from within the serialEvent(..) method.
Something like this:
public void serialEvent(SerialPortEvent spe) {
int data;
String r;
try
{
int len = 0;
while ( ( data = in.read()) > -1 )
{
buffer[len++] = (byte) data;
}
r = new String(buffer,0,len);
System.out.println("this is input stream msg"+r);
}
catch ( IOException e )
{
e.printStackTrace();
System.exit(-1);
}
}
Secondly, you can put in a long sleep, e.g. Thread.sleep(100000);, in the main method, before
calling f.closePort();.
Or, potentially the serialEvent(..) method could close the port after receiving the inputStream's data.
Hope this helps!

Categories