Reading and returning multiple bin files - java

private static int count = 0;
public static String[] play()throws Exception{
File file=new File("E:/proj/"+count+".bin");
FileInputStream fin=new FileInputStream("E:/proj/"+count+".bin");
//reading the byte content of the bin files
byte fileContent[] = new byte[(int)file.length()];
fin.read(fileContent);
//storing the deserialized object that is returned to an object.
Object obj=serializer.toObject(fileContent);
//converting the obtained object to string
String word=obj.toString();
String[] args=new String[]{word};
count++;
return args ;
}
This snippet was actually supposed to read all the bin files present in that specified path and eventually convert it to string and store all the byte[] converted to strings as different string elements in a string[] return the string[]. Though it reads all the bin files owing to the counter, somehow, it returns only string of the 1st binary file it reads.
Even this modified version dosent seem to work. I guess it reads all the bin files, but returns only the string of the last bin file read. What i was trying out for was, to store all the string elements to the string[] and return the string[] to another calling function.
public static String[] play(){
int i = 1;
String[] args=null;;
String result = null;
while (true) {
try {
result += processFile(i++);
args=new String[]{result};
}
catch (Exception e) {
System.out.println("No more files");
break;
}
}
return args;
}
private static String processFile(int fileNumber) throws Exception {
File file=new File("E:/proj/"+fileNumber+".bin");
FileInputStream fin=new FileInputStream("E:/proj/"+fileNumber+".bin");
//reading the byte content of the bin files
byte fileContent[] = new byte[(int)file.length()];
fin.read(fileContent);
//storing the deserialized object that is returned, to an object.
Object obj=serializer.toObject(fileContent);
//converting the obtained object to string
String word=obj.toString();
return word;
}

If I understand your requirement clearly, you may try changing your code this way:
List<String> args = new ArrayList<String>();
while (true) {
try {
args.add(processFile(i++));
}
catch (Exception e) {
// your code
}
}
String[] array = args.toArray(new String[0]);

There are several problems in the code you just posted:
- result is initialised to null so your code will throw a NPE in the first loop.
- assuming you initialise it properly (in your case to ""), args is reallocated to a new array on each loop so you lose the information you got from the previous loop.
If you want your play() method to return an array, where each item in the array is the content of one file, this should work. If you want something different you need to explain your requirement more clearly.
public static String[] play() {
int i = 1;
List<String> files = new ArrayList<String>();
while (true) {
try {
files.add(processFile(i++));
} catch (Exception e) {
System.out.println("No more files");
break;
}
}
return files.toArray(new String[0]);
}

Related

Generating n random integers and putting them in a byte array, printing to file

Currently working on a little project; as part of it I am creating a function called randomNumberGenerator which takes one parameter; string fileName which the name of the file/path that the user wants the integers to be written to. 10,000 random integers with a value between 0 and 100,000. From here, I want to convert the integers into an array of 4 bytes; and print the result in the filename which the user has passed into the function.
I've worked out how to generate the random numbers successfully, however I'm not able to convert it to a byte array successfully. Below is the function so far:
public void randomNumberGenerator(String fileName) throws FileNotFoundException {
try {
PrintWriter printWriter = new PrintWriter(fileName, StandardCharsets.UTF_8);
Random random = new Random();
for(int i=0; i<10000; i++) {
byte [] bytes = ByteBuffer.allocate(4).putInt(random.nextInt(100000)).array();
printWriter.println(Arrays.toString(bytes));
}
printWriter.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
When I try running my code thus far, I'm getting the error java.lang.NumberFormatException: For input string: "[0, 0, -115, -120]" - I've tried to fix this by doing printWriter.println(Arrays.toString(bytes)); instead, as I thought Arrays.toString was causing the error but I still can't get the function to turn the integers to a byte array succesffuly from there.
If anybody could advise me on what to do or where I'm going wrong, I'd appreciate it.
I believe this is what you were looking for, I'd just like to point out that the byte data type can hold values from -128 to 127 so for this program, you'd likely want to use a short as they can hold up to 32k.
I'll also point out that in most cases you don't need to mark the method as throwing the FNTE as you're already handling the exception within (although you could still mark it as throwing FNTE if you want to further handle it from wherever you're calling it from)
public static void main(String args[]) {
//Call the method, pass in the required args
genRandomNums(5, 4, 10000, "nums.txt");
}
public static void genRandomNums(int amount, int size, int maxVal, String fileName){
try {
//Create a file object and set the path to the passed file name
File file = new File(fileName);
//Create object of filewriter which will be used to write to the file
FileWriter fw = new FileWriter(file);
//Create an object of random, used to generate the random numbers
Random random = new Random();
//This loop controls how many arrays are created
for(int i = 0; i < amount; i++){
//Array to store the temp numbers, change this to int/long if you want to store above 32k value mark
short tempArr[] = new short[size];
//This loop controls setting the actual elements of the array
for (int j = 0; j < size; j++){
tempArr[j] = (short) random.nextInt(maxVal);
}
//Write the array to the file, add a new line so each array is separated
fw.write(Arrays.toString(tempArr) + "\n");
}
//Close and save the file
fw.close();
}catch (IOException ex){
ex.printStackTrace();
}
}
Try it like this. The values will be between -128 and 127 inclusive. Separated by a comma and a space.
public static void randomNumberGenerator(String fileName) throws FileNotFoundException {
Random random = new Random();
try (PrintWriter printWriter = new PrintWriter(fileName, StandardCharsets.UTF_8)) {
printWriter.print(random.nextInt(255)-128);
for(int i=0; i<39_999; i++) {
printWriter.printf(", %d", random.nextInt(255)-128);
}
} catch (IOException ioe) {
ioe.printStackTrace();
}
}

How to read from a file and then analyze this data?

I am a begginer(recently began learning) at programming in Java and I need help.
I have to read from a file, which contains numbers. I would like to make a method for reading from a file. Then I need to analyze this data and write it in another file.
What I strugle with is if I make a method just to read from a file or do I also have to save this read data into a variable. Where should this variable be declared inside a method (if is inside, how do I use it outside), if is outside how do I use it inside a method and also outside. Can anyone help me clarify this? What am I doing wrong?
My code of what I wrote until now. File from which I had to read has houndreds of numbers.
public class Test1 {
public static void main(String[] args) {
String nameFile = "numbers.txt";
File file = new File(nameFile);
String contentFile ="";
}
//Method for reading a .txt file
private static String readFromFile(String nameFile, String contentFile) {
String line = "";
try {
BufferedReader read = new BufferedReader(new FileReader(nameFile));
while((line = read.readLine()) != null) {
line = contentFIle;
}
read.close();
} catch (IOException e) {
System.out.println("There was an error reading from a file");
}
return line;
}
}
Theoretically speaking: mathematical functions get input variables, they preform some transformation on the variables and output the result of the transformation.
For example: f(x) = x - 1, g(x) = x * 2
You can chain functions in a way that one functions output will be the other function input: g(f(2)). In this case, the number 2 is used as an input for function f(x) and the output of f(x) is the input of g(x).
Functions and methods in programming can work in a similar way, but It may be more readable to save function output into meaningful variable names, and then to apply these variables to the next function.
Instead of doing: outputText(processText(readText(someFilename)))
You can write (pseudocode):
someFilename = 'foo'
text = readText(someFilename)
processed = processText(text)
outputText(processed)
In java and in your context this would look like the following:
public class Test1 {
public static void main(String[] args) {
String nameFile = "numbers.txt";
String contentFile = readFromFileByName(nameFile);
String altered = processText(contentFile);
saveToFile(altered, "processed.txt");
}
private static String readFromFileByName(String nameFile) {
String fullRead = "";
try {
File file = new File(nameFile);
BufferedReader read = new BufferedReader(new FileReader(file));
String line; // define line variable
while((line = read.readLine()) != null) {
fullRead += line; // pay attention for the altered code
}
read.close();
} catch (IOException e) {
System.out.println("There was an error reading from a file");
} finally {
return fullRead;
}
}
private static List<Integer> stringToIntList(String string) {
return Arrays
.stream(text.split(", "))
.map(Integer::parseInt)
.collect(Collectors.toList());
}
private static String processText(String text) {
String processed = text.replace('H', 'h'); // Some heavy processing :)
return processed;
}
private static void saveToFile(String text, String fileName) {
// save <text> to file with filename <filename>
}
}
1) Line is the variable that you have read to. So you shouldn't change its value.
line = contentFIle;
if you need only first line this method should look like:
private static String readFromFile(String nameFile) {
String line = "";
try {
BufferedReader read = new BufferedReader(new FileReader(nameFile));
line = read.readLine();
read.close();
} catch (IOException e) {
System.out.println("There was an error reading from a file");
}
return line;
}
if you need a list of this:
List<String> lines = Collections.emptyList();
try {
Files.readAllLines(Paths.get(fileName), StandardCharsets.UTF_8);
} catch (IOException e) {
// do something
e.printStackTrace();
}
return lines;
2) Also you don't call readFromFile function. So you need to change the main method:
public static void main(String[] args) {
String nameFile = "numbers.txt";
String contentFile = readFromFile(nameFile);
}
3)For your particular case, there's no sense to call readFromFile with String contentFile because you don't use this variable.

Change from ArrayList to Array of Strings Java

I have this java method which returns an ArrayList, but I want to return an Array of Strings. The method reads the file words.txt (contains all words with a word on each line), and I want to store those words into an Array of Strings.
Heres the code I already have:
public static ArrayList<String> readFile(){
File myFile=new File("./src/folder/words.txt");
Scanner s1=null;
//Creates ArrayList to store each String aux
ArrayList<String> myWords = new ArrayList<String>();
try {
s1 = new Scanner(myFile);
}catch (FileNotFoundException e) {
System.out.println("File not found");
e.printStackTrace();
}
while(s1.hasNext()){
String aux=s1.next();
System.out.println(aux);
}
s1.close();
return myWords;
}
Can I change this code to return a String []?
You can call List.toArray(String[]) to convert the List<String> to a String[]. I would also prefer a try-with-resources over explicitly closing the Scanner and a List<String> interface. Something like,
public static String[] readFile() { // <-- You could pass File myFile here
File myFile = new File("./src/folder/words.txt");
// Creates ArrayList to store each String aux
List<String> myWords = new ArrayList<>();
try (Scanner s1 = new Scanner(myFile)) {
while (s1.hasNext()) {
String aux = s1.next();
System.out.println(aux);
}
} catch (FileNotFoundException e) {
System.out.println("File not found");
e.printStackTrace();
}
return myWords.toArray(new String[0]);
}
try using a built in function of collections class .
ArrayList<String> stringList = new ArrayList<String>();
stringList.add("x");
stringList.add("y");
stringList.add("z");
stringList.add("a");
/*ArrayList to Array Conversion */
/*You can use the toArray method of the collections class and pass the new String array object in the constructor while making a new String array*/
String stringArray[]=stringList.toArray(new String[stringList.size()]);
for(String k: stringArray)
{
System.out.println(k);
}
Add this at last:
String [] arr = myWords.toArray(new String[myWords.size()]);
return arr;
Or simply,
return myWords.toArray(new String[myWords.size()]);

Unable to output ArrayList contents

I'm reading a txt file wich contains one word in each line, stripping the word from non-alphanumeric characters and storing the results into an Array List.
public class LeeArchivo
{
public static void main(String args[]) throws IOException
{
try
{
BufferedReader lector = null;
List<String> matrix = new ArrayList<String>();
lector = new BufferedReader(new FileReader("spanish.txt"));
String line = null;
while((line = lector.readLine())!=null)
{
//matrix.add(line);
matrix.add((line.split("[^a-zA-Z0-9']").toString()));
}
System.out.println(matrix);
System.out.println(matrix.size());
} catch (IOException e)
{
e.printStackTrace();
}
}
}
when I try to print the contents of the ArrayList all I get is each String Object's memory address. The funny thing is, if I don't split the line ie.: I just matrix.add(line) I get the Strings Ok.
I've tried StringBuilders, Iterators, .toString but nothing works.
Can somebody help me to understand what's going on here?
Thanks.
The line.split("[^a-zA-Z0-9']") call returns a String array. Not a String.
So, you are adding not a String instance to your array list, but the result of String array object toString() method call - the String array object's memory address.
If you need to get the whole string after splitting, you should concatenate all
elements of the array, for example:
while((line = lector.readLine())!=null) {
String[] arr = line.split("[^a-zA-Z0-9']");
String res = "";
for(String s : arr) {
res += s;
}
matrix.add(res);
}

Read .dat file on java gets null

I'm starting with java, and now I'm doing some exercises on read/writing files.
I write strings with this format:
String wordList: word1 word2 word3; word4 word5 word6; code
Then I write this to the file using this code:
public void writeSelling(String wordList) throws IOException {
fileOutPutStream = new FileOutputStream (file);
write= new ObjectOutputStream (fileOutPutStream);
write.writeObject(wordList);
write.close();
contador++;
}
But where I'm not getting able to do it right is when reading it. For now, what I get is a null when reading the content of the file, so I think that I'm doing something wrong on the method.
This is the method I use to read the file:
public ArrayList<Object> readSelling() throws Exception, FileNotFoundException, IOException {
ArrayList<Object> objectList = new ArrayList<Object>();
fileInPutStream = new FileInputStream (file);
read= new ObjectInputStream (fileInPutStream);
for (int i=0; i<contador; i++){
objectList.add(read.readObject());
}
read.close();
return objectList;
}
I call this method this way on the main file:
public static void listSelling(){
ArrayList objects;
try{
objects = sellingObject.readSelling();
for (Iterator it = sellingObject.iterator(); it.hasNext();) {
String s = (String)it.next();
System.out.println(s.toString());
}
}catch(FileNotFoundException fnfe){
System.out.println(fnfe.getMessage());
}catch(IOException ioe){
System.out.println(ioe.getMessage());
}catch(Exception e){
System.out.println(e.getMessage());
}
}
I don't have knowledge enough to work with the Iterator, so maybe I'm not using it right.
UPDATE -- Definition of "file.dat
This file is defined this way in other class:
private final String file;
public WriteReadObject(String file){
this.file= file;
}
Then in the main file is called this way:
static WriteReadObject selling= new WriteReadObject("file.dat");
UPDATE 2 --
I see that when I'm writing to the file, I'm writing a null value, and here is where it fails.
I have this:
String one = word1 word2 word3
String two = word4 word5 word6
Before call the write method to write on the file, I add these 2 strings in another string to get only one string. To do this I've created this method:
public String add(String c, String m){
sellinglist[contador] = c + m;
contador++;
String list= sellinglist[contador];
return list;
}
Where c is string one and m y string two
alexey28 said the right thing - you're rewriting the file and finally there's only the last insertion. Anyway it's not that simple to just change FileOutputStream argument to make it work - you can't just append to an ObjectOuputStream - if you would like to, see here. It will corrupt the stream what will result in StreamCorruptedException.
The best solution would be to open ObjectOutputStream once at the begining, write all objects you want and then close stream.
Update
It all depends on how you receive data which are to be written (If you are writing strings then it would be probably more comfortable to do it not in binary mode but text - here is tutorial which explains how to do that).
If you want code how to simply write list of Strings then you can try this:
/* writing */
public void writeSelling(List<String> wordLists) throws IOException {
fileOutPutStream = new FileOutputStream (file);
write= new ObjectOutputStream (fileOutPutStream);
for (String s : wordLists) {
write.writeObject(s);
}
write.close();
contador++;
}
Now you can change code in the place where you call writeSelling().
/* calling method */
List<String> wordLists = new ArrayList<String>();
{ // it's probably loop
String wordList = // somehow receive list like word1 word2 word3; word4 word5 word6; code
wordLists.add(wordList);
}
writeSelling(wordLists);
The rest remains the same. Don't call writeSelling() method multiple times, just once.
The problem is you are writing single object and try to read an array of objects. Every time you are writing object you rewrite current file. Change openning of output stream to append data to file (but don't forget to clear it when writing first object):
fileOutPutStream = new FileOutputStream (file, contador != 0);

Categories