Printing specific spots on 2D array to text file? Java - 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;

Related

java.io.PrintWriter +print(cArray: char[] ): void

I don't know how to write this line: +print(cArray: char[]): void . I know what I want to do for my homework problem, it's just this array line that the book did a lousy job explaining. If you want to know the problem: Write a program to create a file named Excercise12_15.tx if it does not exist. Write 100 integers created randomly into the file using the test I/O. Integers are seperated by spaces in the file. Read the data back from the file and display the data in increasing order.
package WriteReadData;
import java.util.*;
public class WriteReadData {
public static void main(String[] args) throws Exception
{
java.io.File file = new java.io.File("Excercise12_15.txt");
final int SIZE = 100;
int [] emptyArray = new int[SIZE];
if ( file.exists())
{
System.out.print("File exists");
System.exit(0);
}//end if
try
{
java.io.PrintWriter output = new java.io.PrintWriter(file);
for (int i = 1; i < SIZE; i++)
{
emptyArray[i] = (int)(Math.random() * 100);
output.print(emptyArray: int[]): void
}//end for
}//end try
catch
{
output.close();
}//end catch
}//end main
}//end class
java.io.File file = new java.io.File("C:/Users/someUser/Desktop/Excercise12_15.txt");
final int SIZE = 100;
int [] emptyArray = new int[SIZE];
if ( file.exists())
{
System.out.print("File exists");
System.exit(0);
}//end if
//Place your output variable up here, so that it could be seen in the catch and finally block.
java.io.PrintWriter output = null;
try
{
output = new java.io.PrintWriter(file);
for (int i = 1; i < SIZE; i++)
{
emptyArray[i] = (int)(Math.random() * 100);
//Your issuse was here, you didn't write the array to the file correctly
output.print(emptyArray[i] + " ");
}//end for
}//end try
catch (Exception ex)
{
System.out.println(ex.getMessage());
}//end catch
finally{
//Don't place the close in the catch block, do it in the finally, because it always
//executes even when a catch happens.
output.close();
}
}
This is how to properly write the array to a text file with spaces.

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...

Output to file from arraylist not working - 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();

I am not able to create multiple files to store these values

// I have to implement queing theory in this problem. I have to generate a random value and store the values in a file. I am trying to create multiple files to store the values of different ranges. But I am not able to. I am only able to create the first file that is VariableInputRate.txt and not the other file. I need help to create the other file as well. Otherwise is there any way where I can combine the two values and save it in a single file.
Thanks
String path1 = "c://VariableInputRate(0-10).txt";
for(int i = 0 ; i < x/10 ; i ++ )
{
y= Math.random(); //call a random number generator
//to generate a random number between 0 and 1
if(y <= in_rate1 /(in_rate1 + out_rate))
{
if(pkt_in_q < n)
pkt_in_q ++;
else
pkt_dropped ++;
}
else
{
if(pkt_in_q > 0)
pkt_in_q --;
}
File file = new File(path1);
try {
file.createNewFile();
}
catch (IOException e){
e.printStackTrace();
}
try {
FileWriter fw = new FileWriter(file, true);
BufferedWriter bw = new BufferedWriter(fw);
bw.write("For Event " + (i+1) +" we get: ");
//bw.newLine();
bw.write("No. of packets in the queue = " + pkt_in_q +" and no. of packets dropped = "+ pkt_dropped);
bw.newLine();
bw.flush();
bw.close();
fw.close();
}
catch (IOException e)
{
e.printStackTrace();
}
}
System.out.println("Please take at output 1.");
String path2 = "c://VariableInputRate(10-70).txt"; //Depends on which disk you are using, e.g. C,D,E,F disk
for( int i=j/10 ; i < k/70 ; i ++ )
{
y= Math.random(); //call a random number generator
//to generate a random number between 0 and 1
if(y <= in_rate2 /(in_rate2 + out_rate))
{
if(pkt_in_q < n)
pkt_in_q ++;
else
pkt_dropped ++;
}
else
{
if(pkt_in_q > 0)
pkt_in_q --;
}
File file = new File(path2);
try {
file.createNewFile();
}
catch (IOException e){
e.printStackTrace();
}
try {
FileWriter fw2 = new FileWriter(file, true);
BufferedWriter bw2 = new BufferedWriter(fw2);
bw2.write("For Event " + (i+1) +" we get: ");
//bw.newLine();
bw2.write("No. of packets in the queue = " + pkt_in_q +" and no. of packets dropped = "+ pkt_dropped);
bw2.newLine();
bw2.flush();
bw2.close();
fw2.close();
}
catch (IOException e)
{
e.printStackTrace();
}
}
System.out.println("Please take at output 2.");
First can you try to change / slashes to \ or \\? Second why do you create always new File in loop? Because first only have one path. In loop many time created File file = new File(path1);.
I think better declare new File a created it in outside a loop. What do you think?
Combining them in a single file should be easy:
// Warning: code written of my mind, might not compile!
// imports left out
public class Whatever {
public static void main(String[] args) throws IOException {
String path=System.getProperty("user.home")+"\\output.txt");
File f=new File(path);
OutputStream os=new BufferedOutputStream(new FileOutputStream(f));
// perform whatever computations you want here
String s1=Foo.bar();
os.write(s1.getBytes("UTF-8");
String s2=Bar.foo();
os.write(s2.getBytes("UTF-8");
os.close();
}
}

Why isn't my file write method working?

This method should write random chars, but it doesn't write anything at all. I'm probably doing something stupidly wrong here, but for the life of me I can't find it.
public void writeRandomChunk(String fileName) {
try {
File saveFile = new File(folderName + '/' + fileName);
PrintWriter writer = new PrintWriter(
new BufferedWriter(
new FileWriter(saveFile)));
Random r = new Random(System.currentTimeMillis());
for (int i = 0; i < chunkSize; i++) {
for (int j = 0; j < chunkSize; j++) {
writer.print((char)(r.nextInt(26) + 'a'));
}
writer.println();
}
} catch (Exception e) {
System.out.println("Error in WorldFile writeRandomFile:\n"
+ e.getLocalizedMessage());
}
}
As with any stream (and this applies to most any language), you need to close it when you are done.
Streams are optimized to be fast, and as a consequence, not all of the data you write to them instantly appears in the file. When you close() or flush() a stream, the data is written to the file (or whatever other storage mechanism you are using).
In your case, try the following, instead.
public void writeRandomChunk(String fileName) {
PrintWriter writer = null;
try {
File saveFile = new File(folderName + '/' + fileName);
writer = new PrintWriter(
new BufferedWriter(
new FileWriter(saveFile)));
Random r = new Random(System.currentTimeMillis());
for (int i = 0; i < chunkSize; i++) {
for (int j = 0; j < chunkSize; j++) {
writer.print((char)(r.nextInt(26) + 'a'));
}
writer.println();
}
} catch (Exception e) {
System.out.println("Error in WorldFile writeRandomFile:\n"
+ e.getLocalizedMessage());
} finally {
if (writer != null)
writer.close();
}
}
You need to flush() and/or close() the file at some point.
Haven't closed the writer try it in finally.
finally {
writer.close();
}
you should always close your stream. try this pattern with writers:
PrinterWriter writer = null;
try {
writer = new PrinterWriter(...);
// do your write loop here.
} catch (Exception e) {
// recover from exception.
} finally {
if (writer != null) {
writer.close();
}
}

Categories