Output to file from arraylist not working - java - java

I'm trying to create a program that outputs a bunch of integers from an arraylist to a file, however all I get is a bunch of question marks in the .dat file. Can anyone see what my problem is?
BufferedWriter writer = null;
try {
writer = new BufferedWriter(new FileWriter("energy.dat"));
for(int x = 0; x< energy.size(); x++){
writer.write(energy.get(x));
}
} catch (IOException e) {
System.err.println(e);
} finally {
if (writer != null) {
try {
writer.close();
} catch (IOException e) {
System.err.println(e);
}
}
}

Assuming energy is List<Integer> you're calling BufferedWriter.write(int). This method is not writing a text representation of the number. To write 1 you'd have to call write like this: writer.write((int)'1'). This is not the same as writer.write(1).
Replace
writer.write(energy.get(x));
with
String s = String.valueOf(energy.get(x));
writer.write(s, 0, s.length();

Related

Printing specific spots on 2D array to text file? Java

I'm almost there, but I'm getting an error to delete a catch for exceptions. Second to the last line of code. Also is there any way to only choose specific spots on the array to print out to the text file? Thanks
import java.io.*;
import java.util.*;
public class Project_Space
{
public static void main(String[] args)
{
// 2D Array of Passengers and Pilots objects- the Passengers class is in the Person.java file
Person[][] Members ;
int num_flights= 6; //create the "x" bound/size of the array
int num_passengers= 9; //create the "y" bound/size of the array
Members = new Person[num_flights][num_passengers];
//The Members array at index 0 is the first company
Members[0][0] = new Person.Flight(1); //This spot in the array is for the Company number in the first spot. Everything else are place holders for data that doesn't pertain to the company
Members[0][1] = new Person.Pilots(1,"1877963200","Amadeus","Durrutti","Buckminster Cornwallis","1288211435", 11); //This spot in the array is for the first team member of company #1
Members[0][2] = new Person.Pilots(2,"6054350085","Sirius","Sassafrass","Ali Bababa","1776812631", 9);
Members[0][3] = new Person.Passengers(1,"7065253333","Amy","Hartman","Betty Sue","7708889999", 3, 50000,"0554055405540554");
Members[0][4] = new Person.Passengers(2,"7545251337","Amanda","Zion","Beatrice Twix","7448656577", 4, 2000,"0554055405541111");
Members[0][5] = new Person.Passengers(3,"8904448899","Janet","Graves","Neal Wade","4445556666", 5, 3000, "9031029266161432");
Members[0][6] = new Person.Passengers(4,"8902234567","Kristen","Pickering","Christopher Soto","5685461208", 6, 51500, "0985028135114275");
Members[0][7] = new Person.Passengers(5,"5000893778","Julianna","Estrada","Jill Hansen","2770779833", 7, 0, "0213595590286251");
Members[0][8] = new Person.Passengers(6,"2080670437","Regena","Mckenzie","Vicki Cook","6224215759", 8, 250, "8204699533830238");
....
Arrays.deepToString(Members);
PrintWriter writer;
try
{
writer = new PrintWriter("flightnames.txt");
for (int i = 0; i<Members.length; i++){
for(int j = 0; j<Members.length; j++){
writer.print(Members[i][j] + ",");
}writer.println();
}}
catch (FileNotFoundException e){
System.out.println("Error: " + e.getMessage());
}
finally{if (writer!=null)
writer.close();
catch (Exception e)
{System.out.println("Could not close writer");}
}
}
}
Move your finally block, and it should compile properly. For the future use an IDE and use formatting, it will show you your mistakes faster:)
Arrays.deepToString(Members);
PrintWriter writer;
try {
writer = new PrintWriter("flightnames.txt");
for (int i = 0; i < Members.length; i++) {
for (int j = 0; j < Members.length; j++) {
writer.print(Members[i][j] + ",");
}
writer.println();
}
} catch (FileNotFoundException ex) {
System.out.println("Error: " + ex.getMessage());
} catch(Exception ex){
System.out.println("Could not close writer"+ ex.getMessage());
} finally {
if (writer != null) {
try{
writer.close();
} catch(IOException ex) {
System.out.print("Error while closing file: "+ ex.getMessage())
}
}
}
It seems like what you actually want is this:
...
finally {
if (writer!=null) {
try {
writer.close();
} catch (Exception e) {
System.out.println("Could not close writer");
}
}
}
That is, have a dedicated try/catch around your writer.close() call to report that an error was thrown by closing the writer.
Also, you need to initialise the writer to null. You can't do if (writer!=null) (or indeed anything else with writer) if the writer might never have been assigned.
So change your writer declaration to:
PrintWriter writer = null;

I am not able to write all data to a file

I have written the Java code to read from one file and write to a new file. The file from which I am reading has 5000 lines of records, but when I am writing to a new file I am able to write only between 4700-4900 records.
I think may be I am simultaneously reading from a file and writing to a file, which might be creating a problem.
My code is as follows:
Reading from a file:
public String readFile(){
String fileName = "/home/anand/Desktop/index.txt";
FileReader file = null;
try {
file = new FileReader(fileName);
BufferedReader reader = new BufferedReader(file);
String line = "";
while ((line = reader.readLine()) != null) {
line.replaceAll("ids", "");
System.out.println(line);
returnValue += line + "\n";
}
return returnValue;
} catch (Exception e) {
throw new RuntimeException(e);
} finally {
if (file != null) {
try {
file.close();
} catch (IOException e) {
// Ignore issues during closing
}
}
}
}
Writing to a file:
public void writeFile(String returnValue){
String newreturnValue = returnValue.replaceAll("[^0-9,]", "");
String delimiter = ",";
String newtext ="";
String[] temp;
temp = newreturnValue.split(delimiter);
FileWriter output = null;
try {
output = new FileWriter("/home/anand/Desktop/newinput.txt");
BufferedWriter writer = new BufferedWriter(output);
for(int i =0; i < temp.length ; i++){
writer.write("["+i+"] "+temp[i]);
writer.newLine();
}
} catch (Exception e) {
throw new RuntimeException(e);
} finally {
if (output != null) {
try {
output.close();
} catch (IOException e) {
// Ignore issues during closing
}
}
}
}
I need the suggestion to how to simultaneously read and write to a file.
You need to close writer instead of output. The BufferedWriter may not be writing all of the lines, and won't since you never close it.
You have to close the writer object. The last couple lines probably haven't been flushed onto the text file.
In addition, are you aware of the try-with-resource introduced in Java 7? You can condense your code to this by utilizing it:
public String readFile(){
String fileName = "/home/anand/Desktop/index.txt";
try(BufferedReader reader = new BufferedReader(new FileReader(filename)) {
String line = "";
while ((line = reader.readLine()) != null) {
line.replaceAll("ids", "");
System.out.println(line);
returnValue += line + "\n";
}
return returnValue;
} catch (Exception e) {
throw new RuntimeException(e);
}
}
By doing this, Java will automatically close the reader object for you once the try block completes, regardless of whether or not an exception was thrown. This makes it easier to read your code :)

Issue with using an array to store/print files from Linux

I cant figure out how to loop through this instead of just repeating the code, bugging the hell outta me! FYI assignment has already been turned in using 5 iterations of code, just wanted to learn how to implement the string array holding file contents into a for loop for future knowledge. I have tried for a few hours but it just prints the filename, cant seem to get the file contents.
/*************************************************************************
* LinuxSys.java
*
* This program reads text from a file
**************************************************************************/
import java.util.*;
import java.io.*;
public class LinuxSys {
public static void main (String[] args) {
String systemInfo[] = new String [5];
int i = 0;
// using _ to simulate file paths to test on local cpu, as it is easier/quicker
// than logging onto server/copy pasting code into new pico file
systemInfo[0] = "_proc_sys_kernel_hostname.txt"; //local files
systemInfo[1] = "_proc_meminfo.txt"; //local files
systemInfo[2] = "_proc_version.txt"; //local files
systemInfo[3] = "_proc_sys_kernel_hostname.txt"; //local files
//systemInfo[0] = "_proc_sys_kernel_hostname.txt"; //local files
// 1st try to print server host name file
try {
BufferedReader inputStream =
new BufferedReader(new FileReader(systemInfo[i]));
String line = "blank";
while (line != null) {
if((line = inputStream.readLine()) != null) {
System.out.println(line);
i++; // increment systemInfo[] array position
} // end if
} //end while
System.out.println(); // create space
inputStream.close();
} // end try
catch(FileNotFoundException e) {
System.out.println("File was not found");
System.out.println("or could not be opened");
} //end catch
catch(IOException e) {
System.out.println("Error reading from file");
} //end catch
// 2nd try to print server memory file
{
BufferedReader inputStream =
new BufferedReader(new FileReader(systemInfo[i]));
String line = "blank";
while (line != null) {
if((line = inputStream.readLine()) != null) {
System.out.println(line);
i++; // increment systemInfo[] array position
} // end if
} //end while
System.out.println(); // create space
inputStream.close();
} // end try
catch(FileNotFoundException e) {
System.out.println("File was not found");
System.out.println("or could not be opened");
} //end catch
catch(IOException e) {
System.out.println("Error reading from file");
} //end catch
// 3rd try to print version file
try {
BufferedReader inputStream =
new BufferedReader(new FileReader(systemInfo[i]));
String line = "blank";
while (line != null) {
if((line = inputStream.readLine()) != null) {
System.out.println(line);
i++;
} // end if
} //end while
System.out.println(); // create space
inputStream.close();
} // end try
catch(FileNotFoundException e) {
System.out.println("File was not found");
System.out.println("or could not be opened");
} //end catch
catch(IOException e) {
System.out.println("Error reading from file");
} //end catch
} // end main
} // end class
for(int i=0; i < systemInfo.size; ++i)
{
// the code you want to repeat with i varying each time
}
or
int i=0;
while(i < systemInfo.size)
{
// the code you want to repeat with i varying each time
++i;
}
or
int i=0;
while(i++ < systemInfo.size)
{
// the code you want to repeat with i varying each time
}
or
int i=0;
do
{
// the code you want to repeat with i varying each time
}
while(++i < systemInfo.size)
or...

Can reading the dataset be faster in time and/or better in memory than this?

In Java, here is the code to read a file with a table of integers:
public static int[][] getDataset() {
// open data file to read n and m size parameters
BufferedReader br = null;
try {
br = new BufferedReader(new FileReader(filePath));
} catch (FileNotFoundException e) {
e.printStackTrace();
System.exit(1);
}
// count the number of lines
int i = -1;
String line = null, firstLine = null;
do {
// read line
try {
line = br.readLine();
i++;
if (i == 0) firstLine = line;
} catch (IOException e) {
e.printStackTrace();
System.exit(1);
}
} while (line != null);
// close data file
try {
br.close();
} catch (IOException e) {
e.printStackTrace();
System.exit(1);
}
// check the data for emptiness
if (i == 0) {
System.out.println("The dataset is empty!");
System.exit(1);
}
// initialize n and m (at least the first line exists)
n = i; m = firstLine.split(" ").length;
firstLine = null;
// open data file to read the dataset
br = null;
try {
br = new BufferedReader(new FileReader(filePath));
} catch (FileNotFoundException e) {
e.printStackTrace();
System.exit(1);
}
// initialize dataset
int[][] X = new int[n][m];
// process data
i = -1;
while (true) {
// read line
try {
line = br.readLine();
i++;
} catch (IOException e) {
e.printStackTrace();
System.exit(1);
}
// exit point
if (line == null) break;
// convert a line (string of integers) into a dataset row
String[] stringList = line.split(" ");
for (int j = 0; j < m; j++) {
X[i][j] = Integer.parseInt(stringList[j]);
}
}
// close data file
try {
br.close();
} catch (IOException e) {
e.printStackTrace();
System.exit(1);
}
return X;
}
Dataset size parameters n and m are of type static final int and declared outside as well as static final String filePath.
I give you my solution (maybe will be useful for newbies later coming to read this) and ask if it is possible to make it faster in time and/or consuming less memory? I'm interested in perfect micro-optimization, any advice would be great here. In particular I do not like the way the file is opened twice.
Read the file only once and add all lines to an ArraList<String>.
ArrayList grows automatically.
Later process that ArrayList to split the lines.
Further optimisations:
Strimg.split uses a huge regular expression analyzer. Try it with StringTokenizer or your own stringsplit method.
Instead of ArrayList you could avoid overhead by using GrowingIntArray,or GrowingStringArray, these avoid some overhead but are less handy.
speed and mempory usage are contradicting, often you cannot optimize both.
You can save memor by using a one dimesnional array, in java 2d arrays need more space becauseeach column is an object.
access one dim array by X[col + row *rowsize].

Appending a text file with a 2D array

I have a method to store the input of a 2D array in a .txt file. However, even with the true put on the end of FileWriter fw = new FileWriter("CBB.dat");, something that usually allows for appending in past projects, the file still only receives one entry before writing over it with the next entry. How would this be fixed?
public void Save(String[][] EntryList)
{
try
{
File file = new File("CBB.dat");
// if file doesnt exists, then create it
if (!file.exists())
{
file.createNewFile();
}
if (EntryList[0][0] != null)
{
DataOutputStream outstream;
outstream = new DataOutputStream(new BufferedOutputStream(new FileOutputStream(file)));
for (int row = 0; row < EntryList.length; row++)
{
for (int col = 0; col < EntryList[row].length; col++)
{
if (EntryList[row][col] != null) outstream.writeUTF(EntryList[row][col]);
}
outstream.close();
}
}
else System.out.print("Something is wrong");
} catch (IOException e)
{
e.printStackTrace();
}
}
Use a CharSequence instead of a String[][] (or you could also use variable arity parameters):
public static void save(CharSequence entryList)
{
BufferedReader read;
BufferedWriter write;
File file = new File("CBB.dat");
if (!file.exists())
{
try
{
file.createNewFile();
} catch (Exception e)
{
e.printStackTrace();
}
}
try
{
read = new BufferedReader(new FileReader(file));
String complete = "";
String line = null;
while ((line = read.readLine()) != null)
{
complete += line + "\n";
}
read.close();
write = new BufferedWriter(new FileWriter(file));
write.append(complete);
write.append(entryList);
write.flush();
write.close();
} catch (Exception e)
{
e.printStackTrace();
}
}

Categories