Java BufferedInputStream not reading the file - java

Need your help guys.The problem I have is in my code.While I am using RandomAccessFile I don't have any problem in writing or reading the file.But if I am trying to use ObjectInputStream with BufferedInputStream the file can't be read fully(only the first Object).
Here is my code of 2 different ways of reading and writing through stream or RandomAccessFile
public static final String FNAME1 = "1.dat";
public static final String FNAME2 = "2.dat";
final static int ID_SIZE = 10;
final static int NAME_SIZE = 20;
final static int GRADE_SIZE = 5;
final static int RECORD_SIZE = (ID_SIZE + NAME_SIZE + GRADE_SIZE) * 2; // *2 because of the UNI-CODE.
private static Scanner s = new Scanner(System.in);
public static void main(String[] args){
int studNum;
System.out.println("Please enter how many students: ");
studNum=s.nextInt();
Student<?>[] a = new Student[studNum];
try{
createArrary(a,studNum);
save(a,FNAME1);
System.out.println("2.dat saved successfully!! \n");
fileCopy(FNAME1,FNAME2);
System.out.println("The Students in file: ");
read(FNAME2);
bubbleSort(FNAME1);
fileCopy(FNAME1,FNAME2);
System.out.println("2.dat after sorting:");
read(FNAME2);
}catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
/**Creates array of Students.*/
public static Student<?>[] createArrary(Student<?>[] a,int studNum) {
String input="";
for(int i = 0; i < studNum; i++) {
System.out.println("Student # "+(i+1)+":");
System.out.print("\nPlease enter the student's id: ");
int id = s.nextInt();
System.out.print("\nPlease enter Student's name : ");
s.nextLine();
String name = s.nextLine();
System.out.print("\nPlease enter Student's grade ");
input=s.nextLine();
if(isInteger(input)){
a[i]=new Student<>(id, name,Integer.parseInt(input));
}else{
a[i]=new Student<>(id,name,input);
}
}
return a;
}
/**Check if string has integer num.*/
public static boolean isInteger(String s) {
try {
Integer.parseInt(s);
} catch(NumberFormatException e) {
return false;
} catch(NullPointerException e) {
return false;
}
return true;
}
/**Save Student array to the file.*/
public static void save(Student<?>[] a,String fileName) throws FileNotFoundException, IOException {
try (RandomAccessFile f = new RandomAccessFile(fileName, "rw")) {
f.setLength(0);
for (Student<?> p : a) {
writeFixedLengthString(String.valueOf(p.getId()),ID_SIZE,f);
writeFixedLengthString(p.getFullName(),NAME_SIZE,f);
writeFixedLengthString(String.valueOf(p.getGrade()),GRADE_SIZE,f);
}
}
}
public static void save(Student<?>[] a,String fileName) throws FileNotFoundException, IOException {
try(ObjectOutputStream o = new ObjectOutputStream(new BufferedOutputStream(new FileOutputStream(fileName)))){
for(Student<?> p : a){
writeFixedLengthString(String.valueOf(p.getId()),ID_SIZE,o);
writeFixedLengthString(p.getFullName(),NAME_SIZE,o);
writeFixedLengthString(String.valueOf(p.getGrade()),GRADE_SIZE,o);
}
}
}
/**Read Students from file.*/
public static void read(String fileName) throws FileNotFoundException, IOException,NumberFormatException {
try (RandomAccessFile f = new RandomAccessFile(fileName, "r")) {
while (f.getFilePointer() < f.length()) {
int id=Integer.parseInt(readFixedLengthString(ID_SIZE,f));
String name=readFixedLengthString(NAME_SIZE,f);
String grade=readFixedLengthString(GRADE_SIZE,f);
System.out.println(new Student<>(id, name,grade));
}
}
}
public static void read(String fileName) throws FileNotFoundException, IOException,NumberFormatException {
BufferedInputStream f;
try(ObjectInputStream i = new ObjectInputStream(f = new BufferedInputStream(new FileInputStream(fileName)))){
while (f.available() > 0) {
int id=Integer.parseInt((readFixedLengthString(ID_SIZE,i)));
String name=readFixedLengthString(NAME_SIZE,i);
String grade=readFixedLengthString(GRADE_SIZE,i);
System.out.println(new Student<>(id, name,grade));
}
}
}
/** Write fixed number of characters to a DataOutput stream */
public static void writeFixedLengthString(String s, int size,
DataOutput out) throws IOException
{ char[] chars = new char[size];
s.getChars(0, Math.min(s.length(), size), chars, 0);
for (int i = s.length(); i < size; i++)
chars[i] = ' ';
out.writeChars(new String(chars));
}
/** Read fixed number of characters from a DataInput stream */
public static String readFixedLengthString(int size, DataInput in)
throws IOException
{ char[] chars = new char[size];
for (int i = 0; i < size; i++)
chars[i] = in.readChar();
return new String(chars).replaceAll(" ", "");
}
/** Copying source file to destination file */
public static void fileCopy(String fileSource,String fileDest) throws FileNotFoundException,IOException{
try(BufferedInputStream input=new BufferedInputStream(new FileInputStream(fileSource));BufferedOutputStream output =new BufferedOutputStream(new FileOutputStream(fileDest));){
int r;
while ((r = input.read()) != -1)
{ output.write(r);
}
}
}
/** Read Students from file and returns Object */
public static <T> Student<?> readSort(RandomAccessFile f) throws FileNotFoundException, IOException,NumberFormatException {
int id=Integer.parseInt(readFixedLengthString(ID_SIZE,f));
String name=readFixedLengthString(NAME_SIZE,f);
String grade=readFixedLengthString(GRADE_SIZE,f);
return new Student<>(id, name,grade);
}
/** Receive Student Objects and Save them to file */
public static <T> void saveSort(Student<T> stud,RandomAccessFile f) throws FileNotFoundException, IOException {
writeFixedLengthString(String.valueOf(stud.getId()),ID_SIZE,f);
writeFixedLengthString(stud.getFullName(),NAME_SIZE,f);
writeFixedLengthString(String.valueOf(stud.getGrade()),GRADE_SIZE,f);
}
/** Bubble Sort of Student's grades */
#SuppressWarnings("unchecked")
public static <T> void bubbleSort(String file) throws FileNotFoundException, IOException {
try (RandomAccessFile raf = new RandomAccessFile(file, "rw")) {
boolean needNextPass = true;
for (int k = 1; k < raf.length() / RECORD_SIZE && needNextPass; k++) {
needNextPass = false;
for (int i = 0; i < (raf.length() / RECORD_SIZE) - k; i++) {
raf.seek(RECORD_SIZE * i);
long tmpPrev = raf.getFilePointer();
Student<T> prevStud = (Student<T>) readSort(raf);
long tmpNext = raf.getFilePointer();
Student<T> nextStud = (Student<T>) readSort(raf);
if(isInteger((String) prevStud.getGrade())&&isInteger((String) nextStud.getGrade())){
if(Integer.parseInt((String) prevStud.getGrade())>Integer.parseInt((String) nextStud.getGrade())){
Student<T> temp=prevStud;
prevStud = nextStud;
nextStud = temp;
raf.seek(tmpPrev);
saveSort(prevStud, raf);
raf.seek(tmpNext);
saveSort(nextStud, raf);
needNextPass = true;
}
}else if(String.valueOf(prevStud.getGrade())
.compareTo(String.valueOf(nextStud.getGrade())) > 0 &&!isInteger((String) prevStud.getGrade())&&!isInteger((String) nextStud.getGrade())){
Student<T> temp=prevStud;
prevStud = nextStud;
nextStud = temp;
raf.seek(tmpPrev);
saveSort(prevStud, raf);
raf.seek(tmpNext);
saveSort(nextStud, raf);
needNextPass = true;
}else if(isInteger((String) prevStud.getGrade())&&!isInteger((String) nextStud.getGrade())||!isInteger((String) prevStud.getGrade())&&isInteger((String) nextStud.getGrade())&&String.valueOf(prevStud.getGrade())
.compareTo(String.valueOf(nextStud.getGrade())) < 0){
Student<T> temp=prevStud;
prevStud = nextStud;
nextStud = temp;
raf.seek(tmpPrev);
saveSort(prevStud, raf);
raf.seek(tmpNext);
saveSort(nextStud, raf);
needNextPass = true;
}
}
}
}
}
}

ok I understand I can just write like this.
public static void read(String fileName) throws FileNotFoundException, IOException,NumberFormatException {
try(ObjectInputStream i = new ObjectInputStream(new BufferedInputStream(new FileInputStream(fileName)))){
while (i.available()>0) {
int id=Integer.parseInt((readFixedLengthString(ID_SIZE,i)));
String name=readFixedLengthString(NAME_SIZE,i);
String grade=readFixedLengthString(GRADE_SIZE,i);
System.out.println(new Student<>(id, name,grade));
}
}
}
But how I can translate inputstream to RandomAccessFile ?

Related

Storing text file as 2D character array

I have a text file:
##########
#.......*#
#.########
#........#
########.#
##.......#
##########
How can I get this to be represented as a 2D character array like this:
char[][] maze = {{##########},
{#.......*#},
{#.########},
{#........#},
{########.#},
{##.......#},
{##########}};
I'm also using a JFileChooser to get the text file and saving it as a java.io.File.
Here's what I have that finds the rows/columns and attempts to store the text file as a 2D char array.
import javax.swing.*;
import java.io.*;
import java.util.*;
/**
* Created by marcusstone on 9/10/15.
*/
public class MazeReader {
public static int colNum;
public static int rowNum;
public static int levels;
public static File textFile;
public char[][] maze = new char[rowNum][colNum];
public int getRows() {
return rowNum;
}
public int getCols() {
return colNum;
}
public void loadFile() {
JFileChooser chooseFile = new JFileChooser();
if (chooseFile.showOpenDialog(null) == JFileChooser.APPROVE_OPTION) {
textFile = chooseFile.getSelectedFile();
} else {
textFile = null;
}
}
public void getMazeInfo() {
try {
Scanner myScanner = new Scanner(textFile);
String firstLine = myScanner.nextLine();
colNum = firstLine.length();
rowNum = 1;
levels = 1;
while (myScanner.hasNextLine()) {
String aLine = myScanner.nextLine();
if (aLine.charAt(0) != '-') {
rowNum++;
}
if (aLine.charAt(0) == '-') {
levels++;
}
}
} catch (IOException e) {
e.printStackTrace();
}
}
public void getMazeCharArray() throws IOException {
try {
BufferedReader reader = new BufferedReader(new FileReader(textFile));
String line = null;
int x = 0, y = 0;
//draw the maze
for(int i = 0; i < rowNum; i ++){
line = reader.readLine();
System.out.println(line);
}
//add elements to the maze array
for(int i = 0; i < rowNum; i++){
for(int j = 0; j < colNum; j++){
maze[i]=line.toCharArray();
}
}
}catch(IOException e) {
e.printStackTrace();
}
}
public static void main (String[] args) throws IOException {
MazeReader myMazeReader = new MazeReader();
myMazeReader.loadFile();
myMazeReader.getMazeInfo();
System.out.println(rowNum);
System.out.println(colNum);
myMazeReader.getMazeCharArray();
} // end main
} // end class
First you put some tried material, but nevertheless here:
First load file and read from that. Reading data, put into two -dimensional array, with x = y = your boundary,
char[x][y] maze;
.

Appending an array to a binary file

Hi there I have been having trouble appending entered data to the end of a binary file, having looked up how to do so I found a solution here on stack overflow:
try {
ObjectOutputStream out = new ObjectOutputStream (new FileOutputStream ("BinaryWrite.hagl", true));
out.writeObject(allTowns);
out.flush ();
}
catch (Exception e){
System.out.println("IMPOSSSIBLE");
}
In this piece of code allTowns is my array in which the data I wish to add is held. The problem I am getting is that when I run my program and it displays what is in the file at the end this piece of code never writes to the file at all, I was wondering if anyone could help me understand why this does not work or even just recommend a different method if necessary.
My full code (this part is currently commented out so one can easily create the file):
import java.util.*;
import java.io.*;
public class CoastaslTowns implements Serializable
{
public static Scanner input = new Scanner(System.in);
String name, county;
int population, area;
public static int count = 0;
public static int continuation = 0;
public static CoastaslTowns[] allTowns = new CoastaslTowns[50];
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int loop1 = 0;
for (int i=0; i < 50; i++) {
allTowns[i] = new CoastaslTowns();
}
while (loop1 == 0) {
System.out.println("Please enter the name of the town.");
String nameEntered = input.nextLine();
System.out.println("Please enter the county in which the town resides.");
String countyEntered = input.nextLine();
System.out.println("Please enter the population of the town.");
int populationEntered = input.nextInt();
System.out.println("Please enter the area of the town.");
int areaEntered = input.nextInt();
input.nextLine();
System.out.println("Are you satisfied with your entries?");
String satisfaction = input.nextLine();
if (satisfaction.equals("yes")) {
loop1 = 5;
System.out.println("Thank you for entering your details");
continuation = 1;
}
else if (satisfaction.equals("no")) {
System.out.println("Would you like to continue and enter more towns?");
String countychecker = input.nextLine();
if (countychecker.equals("yes")) {
}
else {
break;
}
}
writeToFile(nameEntered, countyEntered, populationEntered, areaEntered);
}
ReturnTowns();
}
public static void inputVariations(){
}
public static void writeToFile(String nameEntered, String countyEntered, int populationEntered, int areaEntered) {
int loop2 = 0;
while (loop2 == 0){
allTowns[count].population = populationEntered;
allTowns[count].name = nameEntered;
allTowns[count].county = countyEntered;
allTowns[count].area = areaEntered;
if (continuation == 1) {
loop2 = 1;
}
else {
loop2 = 1;
}
count = count + 1;
}
try {
FileOutputStream fileOut = new FileOutputStream("BinaryWrite.hgal");
ObjectOutputStream out = new ObjectOutputStream(fileOut);
out.writeObject(allTowns);
out.close();
fileOut.close();
} catch (IOException i) {}
/*
try {
ObjectOutputStream out = new ObjectOutputStream (new FileOutputStream ("BinaryWrite.hagl", true));
out.writeObject(allTowns);
out.flush ();
}
catch (Exception e){
System.out.println("IMPOSSSIBLE");
}
*/
}
public static void ReturnTowns(){
{
int x = 0;
CoastaslTowns[] bw = null;
try {
FileInputStream fileIn =
new FileInputStream("BinaryWrite.hgal");
ObjectInputStream in = new ObjectInputStream(fileIn);
bw = (CoastaslTowns[]) in.readObject();
while (bw[x].population != 0) {
System.out.println(bw[x].name);
System.out.println(bw[x].county);
System.out.println(bw[x].population);
System.out.println(bw[x].area);
System.out.println();
x++;
}
in.close();
fileIn.close();
} catch (IOException i) {
} catch (ClassNotFoundException c) {
}
}
}
}
Any help would be greatly appreciated.

Exception in thread "main" java.lang.RuntimeException: Uncompilable source code - illegal start of expression

I'm getting an error can someone help me with the following code:
it is supposed to perform preprocesing
// program to perform preprocess
public static void main(String[] args) {
//public class PreProcess {
// Read a file into a string. Takes file path, returns string
/**
*
* #param path
* #return
*/
public String readFileIntoString(String path) {
char[] line = new char[1024];
StringBuilder dataString;
dataString = new StringBuilder(5000);
try {
try (BufferedReader input = new BufferedReader(new FileReader(path))) {
while (true) {
int readLength = input.read(line);
if (readLength == -1)
break;
dataString.append(line, 0, readLength);
}
}
return dataString.toString();
}
catch (IOException e) {
return " ";
}
}
// Removes stop words from a string. Takes stop word file path and returns
// string
public static String removeStopWords(String fileData, String stopWordFilePath) {
String newfile = fileData;
String line;
try {
BufferedReader input = new BufferedReader(new FileReader(stopWordFilePath));
while ((line = input.readLine()) != null) {
if (line.compareTo("") == 0)
continue;
line = " " + line + " ";
newfile = newfile.replaceAll(line, " ");
}
input.close();
}
catch (IOException e) {
e.printStackTrace();
}
return newfile;
}
public static String removeHTMLTags(String fileData) {
return strip(fileData);
}
// Filtering to a given windowsize for query terms. Takes query and size,
// returns string
public static String filterToWindow(String query, String fileData, int windowSize) {
StringBuffer dataString = new StringBuffer(5000);
String[] fileWords = fileData.split(" ");
String[] queryWords = query.split(" ");
int[] markWords = new int[fileWords.length];
for (int i = 0; i < fileWords.length; i++) {
markWords[i] = 0;
}
for (int i = 0; i < fileWords.length; i++) {
for (int j = 0; j < queryWords.length; j++) {
if (fileWords[i].compareTo(queryWords[j]) == 0) {
for (int k = 0; k < windowSize; k++) {
if (i + k < fileWords.length)
markWords[i + k] = 1;
if (i - k > 0)
markWords[i - k] = 1;
}
}
}
}
for (int i = 0; i < fileWords.length; i++) {
if (markWords[i] == 1) {
dataString.append(fileWords[i]);
dataString.append(" ");
}
}
return dataString.toString();
}
public static void extractMetaData(String fileData, String linkFilePath, int docId) {
int urlEnd = 0, urlStart = 0;
StringBuilder b3 = new StringBuilder();
StringBuilder b2 = new StringBuilder();
fileData = fileData.toLowerCase();
try {
String title = fileData.substring(fileData.indexOf("<title"), fileData.indexOf("</title>")).replaceAll("\\<.*?>", "");
writeStringIntoFile(title, linkFilePath + docId + ".title");
}
catch (Exception e) {
}
while (true) {
urlStart = fileData.indexOf("a href=\"", urlEnd) + 8;
if (urlStart == 7)
break;
urlEnd = fileData.indexOf('\"', urlStart + 1);
String link = fileData.substring(urlStart, urlEnd);
int linkstart = 0;
int linkend = link.length() - 1;
if (link.startsWith("http"))
link = link.substring(7);
while (link.startsWith("/"))
link = link.substring(1);
if (!link.startsWith("#")) {
if (link.indexOf('/') != -1)
link = link.substring(0, link.indexOf('/'));
if (!link.contains("wiki") && !link.contains("myspace.com") && !link.contains("javascript")) {
b3.append(link);
b3.append("\n");
}
}
}
writeStringIntoFile(b3.toString(), linkFilePath + docId + ".links");
urlEnd = 0;
while (true) {
urlStart = fileData.indexOf("src=\"", urlEnd) + 5;
if (urlStart == 4)
break;
urlEnd = fileData.indexOf('\"', urlStart + 1);
String link = fileData.substring(urlStart, urlEnd);
if (!link.startsWith("#")) {
if (!link.startsWith("/")) {
link = link.substring(0, link.lastIndexOf('/') + 1);
}
b2.append(link);
b2.append("\n");
}
}
writeStringIntoFile(b2.toString(), linkFilePath + docId + ".images");
}
// Saves a string to a file. Takes string and file path
public static void writeStringIntoFile(String fileData, String path) {
try {
try (BufferedWriter output = new BufferedWriter(new FileWriter(path))) {
output.write(fileData);
}
}
catch (IOException e) {
}
}
private static String strip(String inputString) {
inputString = inputString.replaceAll("\\<style.*?</style>", " ");
inputString = inputString.replaceAll("\\<script.*?</script>", " ");
inputString = inputString.replaceAll("\\<.*?>", " ").replaceAll("[^A-Za-z]+", " ").replaceAll("\\s+", " ");
inputString = inputString.trim();
// inputString = PorterStemmer.applyStemmer(inputString);
return inputString;
}
}
}
You've declared methods inside your main()
public static void main(String[] args) {
public String readFileIntoString(String path) {
char[] line = new char[1024];
StringBuilder dataString;
...
You cannot do this. Methods cannot be nested inside methods. Take them out
public static void main(String[] args) {
...
}
public String readFileIntoString(String path) {
char[] line = new char[1024];
StringBuilder dataString;
...

File transfer over socket using JAVA

I was searching a code in java for sending multiple files over a socket, I found this code which consists of a TX main, a RX main and a class for all the dirty work I assume. Code runs with no errors but I have a questions for the experts,
where exactly in the code, the user types the files that he/she want to send to the server ?
And in the server main, what is the location where the server stores the received file, and with what name ?
Where exactly in this code ( TX / RX / ByteStream), should I amend to specify what file goes in ?
I would like to input the filename myself in the client (TX) side, where futher on I would include a JFileChooser for the user to select Graphically which file to send.
package file_rx;
import java.io.*;
import java.net.*;
public class File_RX implements Runnable
{
private static final int port = 4711;
private Socket socket;
public static void main(String[] _)
{
try
{
ServerSocket listener = new ServerSocket(port);
while (true)
{
File_RX file_rec = new File_RX();
file_rec.socket = listener.accept();
new Thread(file_rec).start();
}
}
catch (java.lang.Exception e)
{
e.printStackTrace(System.out);
}
}
public void run()
{
try
{
InputStream in = socket.getInputStream();
int nof_files = ByteStream.toInt(in);
for (int cur_file = 0; cur_file < nof_files; cur_file++)
{
String file_name = ByteStream.toString(in);
File file = new File(file_name);
ByteStream.toFile(in, file);
}
}
catch (java.lang.Exception e)
{
e.printStackTrace(System.out);
}
}
}
package file_tx;
import java.io.*;
import java.net.*;
public class File_TX
{
private static final int port = 4711;
private static final String host = "localhost";
public static void main(String[] args)
{
try
{
Socket socket = new Socket(host, port);
OutputStream os = socket.getOutputStream();
int cnt_files = args.length;
ByteStream.toStream(os, cnt_files);
for (int cur_file = 0; cur_file < cnt_files; cur_file++)
{
ByteStream.toStream(os, args[cur_file]);
ByteStream.toStream(os, new File(args[cur_file]));
}
}
catch (Exception e)
{
e.printStackTrace();
}
}
}
package file_rx;
import java.io.*;
public class ByteStream
{
private static byte[] toByteArray(int in_int)
{
byte a[] = new byte[4];
for (int i = 0; i < 4; i++)
{
int b_int = (in_int >> (i*8)) & 255;
byte b = (byte) (b_int);
a[i] = b;
}
return a;
}
private static int toInt(byte[] byte_array_4)
{
int ret = 0;
for (int i = 0; i < 4; i++)
{
int b = (int) byte_array_4[i];
if (i < 3 && b < 0)
{
b = 256 + b;
}
ret += b << (i * 8);
}
return ret;
}
public static int toInt(InputStream in) throws java.io.IOException
{
byte[] byte_array_4 = new byte[4];
byte_array_4[0] = (byte)in.read();
byte_array_4[1] = (byte)in.read();
byte_array_4[2] = (byte)in.read();
byte_array_4[3] = (byte)in.read();
return toInt(byte_array_4);
}
public static String toString(InputStream ins) throws java.io.IOException
{
int len = toInt(ins);
return toString(ins, len);
}
private static String toString(InputStream ins, int len) throws java.io.IOException
{
String ret = new String();
for (int i = 0; i < len; i++)
{
ret += (char) ins.read();
}
return ret;
}
public static void toStream(OutputStream os, int i) throws java.io.IOException
{
byte [] byte_array_4 = toByteArray(i);
os.write(byte_array_4);
}
public static void toStream(OutputStream os, String s) throws java.io.IOException
{
int len_s = s.length();
toStream(os, len_s);
for (int i = 0; i < len_s; i++)
{
os.write((byte) s.charAt(i));
}
os.flush();
}
private static byte[] toByteArray(InputStream ins, int an_int) throws java.io.IOException
{
byte[] ret = new byte[an_int];
int offset = 0;
int numRead = 0;
int outstanding = an_int;
while ((offset < an_int) && (numRead = ins.read(ret, offset, outstanding)) > 0)
{
offset += numRead;
outstanding = an_int - offset;
}
if (offset < ret.length)
{
//throw new Exception("Could not completely read from stream, numRead =" + numRead + ", ret.lenght = " + ret.length);
}
return ret;
}
private static void toFile(InputStream ins, FileOutputStream fos, int len, int buf_size) throws java.io.IOException, java.io.FileNotFoundException
{
byte[] buffer = new byte[buf_size];
int len_read = 0;
int total_len_read = 0;
while (total_len_read + buf_size <= len)
{
len_read = ins.read(buffer);
total_len_read += len_read;
fos.write(buffer, 0, len_read);
}
if (total_len_read < len)
{
toFile(ins, fos, len - total_len_read, buf_size / 2);
}
}
private static void toFile(InputStream ins, File file, int len) throws java.io.IOException, java.io.FileNotFoundException
{
FileOutputStream fos = new FileOutputStream(file);
toFile(ins, fos, len, 1024);
}
public static void toFile (InputStream ins, File file) throws java.io.IOException, java.io.FileNotFoundException
{
int len = toInt(ins);
toFile(ins, file, len);
}
public static void toStream(OutputStream os, File file) throws java.io.IOException, java.io.FileNotFoundException
{
toStream(os, (int) file.length());
byte b[] = new byte[1024];
InputStream is = new FileInputStream(file);
int numRead = 0;
while ((numRead = is.read(b)) > 0)
{
os.write(b, 0, numRead);
}
os.flush();
}
}
The names (and paths) of the files to be transmitted are specified as arguments to the main method in the File_TX class. On the server side (File_RX class), the files will be saved relatively to the current directory of the File_RX.class file, having the same relative path as the input arguments above.

Cannnot find "Array Out of Bounds Exception" Java

I am creating a search engine that reads in a text file, and prints out a word that a user can search for. I'm currently creating an index of arrays to be searched for. More information can be found here: http://cis-linux1.temple.edu/~yates/cis1068/sp12/homeworks/concordance/concordance.html
When I run this program right now, I get an "Array Index Out of Bounds Exception"
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 43
at SearchEngine.main(SearchEngine.java:128)
Can anyone help debug?
import java.util.*;
import java.io.*;
public class SearchEngine {
public static int getNumberOfWords (File f) throws FileNotFoundException {
int numWords = 0;
Scanner scan = new Scanner(f);
while (scan.hasNext()) {
numWords++;
scan.next();
}
scan.close();
return numWords;
}
public static void readInWords (File input, String [] x) throws FileNotFoundException {
Scanner scan = new Scanner(input);
int i = 0;
while (scan.hasNext() && i<x.length) {
x[i] = scan.next();
i++;
}
scan.close();
}
public static int getNumOfDistinctWords (File input, String [] x) throws FileNotFoundException {
Scanner scan = new Scanner(input);
int count = 0;
int i = 1;
while (scan.hasNext() && i<x.length) {
if (!x[i].equals(x[i-1])) {
count++;
}
i++;
}
scan.close();
return count;
}
public static void readInDistinctWords (String [] x, String [] y) {
int i = 1;
int k = 0;
while (i<x.length) {
if (!x[i].equals(x[i-1])) {
y[k] = x[i];
k++;
}
i++;
}
}
public static int getNumberOfLines (File input) throws FileNotFoundException {
int numLines = 0;
Scanner scan = new Scanner(input);
while (scan.hasNextLine()) {
numLines++;
scan.nextLine();
}
scan.close();
return numLines;
}
public static void readInLines (File input, String [] x) throws FileNotFoundException {
Scanner scan = new Scanner(input);
int i = 0;
while (scan.hasNextLine() && i<x.length) {
x[i] = scan.nextLine();
i++;
}
scan.close();
}
Main
public static void main(String [] args) {
try {
//gets file name
System.out.println("Enter the name of the text file you wish to search");
Scanner kb = new Scanner(System.in);
String fileName = kb.nextLine();
String TXT = ".txt";
if (!fileName.endsWith(TXT)) {
fileName = fileName.concat(TXT);
}
File input = new File(fileName);
//First part of creating index
System.out.println("Creating vocabArray");
int NUM_WORDS = getNumberOfWords(input);
//System.out.println(NUM_WORDS);
String [] wordArray = new String[NUM_WORDS];
readInWords(input, wordArray);
Arrays.sort(wordArray);
int NUM_DISTINCT_WORDS = getNumOfDistinctWords(input, wordArray);
String [] vocabArray = new String[NUM_DISTINCT_WORDS];
readInDistinctWords(wordArray, vocabArray);
System.out.println("Finished creating vocabArray");
System.out.println("Creating concordanceArray");
int NUM_LINES = getNumberOfLines(input);
String [] concordanceArray = new String[NUM_LINES];
readInLines(input, concordanceArray);
System.out.println("Finished creating concordanceArray");
System.out.println("Creating invertedIndex");
int [][] invertedIndex = new int[NUM_DISTINCT_WORDS][10];
int [] wordCountArray = new int[NUM_DISTINCT_WORDS];
int lineNum = 0;
while (lineNum<concordanceArray.length) {
Scanner scan = new Scanner(concordanceArray[lineNum]);
while (scan.hasNext()) {
int wordPos = Arrays.binarySearch(vocabArray, scan.next());
wordCountArray[wordPos]+=1;
for(int i = 0; i < invertedIndex.length; i++) {
for(int j = 0; j < invertedIndex[i].length; i++) {
if (invertedIndex[i][j] == 0) {
invertedIndex[i][j] = lineNum;
break;
} } }
}
lineNum++;
}
System.out.println("Finished creating invertedIndex");
}
catch (FileNotFoundException exception) {
System.out.println("File Not Found");
}
} //main
} //class
for(int j = 0; j < invertedIndex[i].length; i++) {
should probably be
j++
not
i++
Update after your fix.
That means that Arrays.binarySearch(vocabArray, scan.next()) is not finding the item being searched for. You cannot assume that the vocabArray has the item you are searching for. You will need to add an if(... < 0) for the binarySearch call.

Categories