im trying to run a simulator and there are several problems, primarily....
-the code isn't printing out the values at the end of the program
- the code does not actually create the file
-I'm pretty tired so forgive any foolish mistakes I made or details I have left out.
I've searched the website and I found this
What is the simplest way to write a text file in java
and
how to write to text file outside of netbeans
I thought i could edit code from the first link to work for me, but that did not work( whcih is what you see here)
the second page looks more simple but there's no surrounding code so im not sure what the context is and how I would implement it
import java.util.Random;
import java.util.Scanner;
import java.io.*;
/*
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
*/
public class SimClass {
public static void main (String[] args)
{
Scanner keyboard = new Scanner(System.in) ;
Random randomNumbers = new Random();
//create object from random class
//create self explanaroty input parameters
int pkt_in_q = 0 ;
int pkt_dropped = 0;
int input ;
int output ;
int buffer ;
int x ;
double y ;
//ask for values for buffer size. input rate, output rate
y = randomNumbers.nextDouble();
//attempt to assign a random number to the variable and
/*here you should get user input.
buffer size, # of repitions , if
*/
//fix this
System.out.print("Enter an integer for the input rate ");
input = keyboard.nextInt();
System.out.print("Enter an integer for the output rate ");
output = keyboard.nextInt();
System.out.print("What is the buffer size ");
buffer = keyboard.nextInt();
for (x = 1000000; x >=0 ; x--)
{ /*
simulate # of packets dropped/in the que,
create file, write results to file, output results,
*/
if (y > input/(output/buffer))
{
if (pkt_in_q < buffer)
{
pkt_in_q++ ;
}
else
{
pkt_dropped++ ;
}
//if statement should terminate here
}
else
if (pkt_in_q > 0)
{
pkt_in_q -- ;
}
}
/*
create file, write results to file, output results,
*/
try { /*this seeems to be the problem, the program is either not doing
anything with this or not making the results visible
*/
String content =( " pkt_in_q is " + pkt_in_q +
"pkt_dropped is " + pkt_dropped);
File file = new File("C:/Temp/inputFile.txt");
// if file doesnt exists, then create it
if (!file.exists())
{
file.createNewFile();
}
FileWriter fw = new FileWriter(file.getAbsoluteFile());
try (BufferedWriter bw = new BufferedWriter(fw))
{
bw.write(content);
bw.close();
}
System.out.println("packets dropped value is = " +
pkt_dropped + "packets in q value is = " + pkt_in_q);
}
catch (IOException e)
{
//e.printStackTrace();
}
}
}
I think Code not executing due to file path error.
File file = new File("C:/Temp/inputFile.txt");
There is no folder called "Temp" in the C: drive. If u create Temp folder manually then the code will execute successfully.
File file = new File("D:/Temp/inputFile.txt");
I have created "Temp" folder in D: drive and code executed successfully.
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
Random randomNumbers = new Random();
//create object from random class
//create self explanaroty input parameters
int pkt_in_q = 0;
int pkt_dropped = 0;
int input;
int output;
int buffer;
int x;
double y;
//ask for values for buffer size. input rate, output rate
y = randomNumbers.nextDouble() * 10;
System.out.println("Y++++++" + y);
//attempt to assign a random number to the variable and
/*here you should get user input.
buffer size, # of repitions , if
*/
//fix this
System.out.print("Enter an integer for the input rate ");
input = keyboard.nextInt();
System.out.print("Enter an integer for the output rate ");
output = keyboard.nextInt();
System.out.print("What is the buffer size ");
buffer = keyboard.nextInt();
for (x = 1000000; x >= 0; x--) { /*
simulate # of packets dropped/in the que,
create file, write results to file, output results,
*/
if (y > input / (output / buffer)) {
if (pkt_in_q < buffer) {
pkt_in_q++;
} else {
pkt_dropped++;
}
//if statement should terminate here
} else if (pkt_in_q > 0) {
pkt_in_q--;
}
}
/*
create file, write results to file, output results,
*/
try { /*this seeems to be the problem, the program is either not doing
anything with this or not making the results visible
*/
String content = (" pkt_in_q is " + pkt_in_q + "pkt_dropped is " + pkt_dropped);
String folderPath = "D:" + File.separator + "Temp";
String fileName = folderPath + File.separator + "inputFile.txt";
File folder = new File(folderPath);
File file = new File(fileName);
folder.mkdir();
// if file doesnt exists, then create it
if (!file.exists()) {
//file.mkdir();
file.createNewFile();
System.out.println("File created");
}
FileWriter fw = new FileWriter(file.getAbsoluteFile());
BufferedWriter bw = new BufferedWriter(fw);
try {
bw.write(content);
bw.close();
} catch (IOException e) {
e.printStackTrace();
}
System.out.println("packets dropped value is = " + pkt_dropped
+ "packets in q value is = " + pkt_in_q);
} catch (IOException e) {
//e.printStackTrace();
}
}
Corrected the code check this and change the file directory and folder directory according to your requirement.
Correction for details:
First you can't define a try block like below
try (BufferedWriter bw = new BufferedWriter(fw))
It should be defined like
try{
}
catch(IOException e)
{
//do something
}
Modified code for that is like below:
FileWriter fw = new FileWriter(file.getAbsoluteFile());
BufferedWriter bw = new BufferedWriter(fw);
try
{
bw.write(content);
bw.close();
}
catch (IOException e)
{
//e.printStackTrace();
}
Second you have to create the directory first post that you can create the file inside the directory. so just modified the code to get the directory created and file created.
String folderPath = "D:" + File.separator + "Temp";
String fileName = folderPath + File.separator + "inputFile.txt";
File folder = new File(folderPath);
File file = new File(fileName);
folder.mkdir();
Hope it clarifies your doubt.
Related
My program stimulates FCFS scheduling algorithm. It takes a .csv file as input and output the average waiting time. I have trouble with inputting the file. This is the error that i get when i ran the code:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 0
at main.FCFS.main(FCFS.java:16)
What am I doing wrong? I cannot seems to figure it out. Please help.
package main;
//programming FCFS scheduling algorithm
import java.util.Scanner;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.File;
import java.io.FileInputStream;
public class FCFS {
public static void main(String[] args) throws FileNotFoundException {
// To Store Name of the file to be opened
String file = args[0];
int i = 0, n;
double AWT = 0, ATT = 0;
int AT[] = new int[100];
int BT[] = new int[100];
int WT[] = new int[100];
int TAT[] = new int[100];
int PID[] = new int[100];
// To open file in read mode
FileInputStream fin = null;
// To read input(file name) from standard input stream
Scanner s = new Scanner(new File("/Users/SLO/ex.csv"));
// To hold each single record obtained from CSV file
String oneRecord = "";
try {
// Open the CSV file for reading
fin = new FileInputStream(file);
// To read from CSV file
s = new Scanner(fin);
// Loop until all the records in CSV file are read
while (s.hasNextLine()) {
oneRecord = s.nextLine();
// Split record into fields using comma as separator
String[] details = oneRecord.split(",");
PID[i] = Integer.parseInt(details[0]);
AT[i] = Integer.parseInt(details[1]);
BT[i] = Integer.parseInt(details[2]);
System.out.printf("Process Id=%d\tArrival Time=%d\tBurst Time=%d\n", PID[i], AT[i], BT[i]);
i++;
}
WT[0] = 0;
for (n = 1; n < i; n++) {
WT[n] = WT[n - 1] + BT[n - 1];
WT[n] = WT[n] - AT[n];
}
for (n = 0; n < i; n++) {
TAT[n] = WT[n] + BT[n];
AWT = AWT + WT[n];
ATT = ATT + TAT[n];
}
System.out.println(" PROCESS BT WT TAT ");
for (n = 0; n < i; n++) {
System.out.println(" " + PID[n] + " " + BT[n] + " " + WT[n] + " " + TAT[n]);
}
System.out.println("Avg waiting time=" + AWT / i);
System.out.println("Avg waiting time=" + ATT / i);
} catch (FileNotFoundException e) {
System.out.printf("There is no CSV file with the name %s", file);
}
finally {
if (fin != null) {
try {
fin.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
Well, an ArrayIndexOutOfBoundsException is thrown if there are no arguments, because you access the empty array at a non existing index. Add the following lines to check if the argument is passed correctly:
...
public static void main(String[] args) throws FileNotFoundException {
if (args.length == 0)
throw new IllegalArgumentException("Missing mandatory file name in argument list");
// To Store Name of the file to be opened
String file = args[0];
...
If the missing argument ist the reason for the failure, check out https://docs.oracle.com/javase/tutorial/essential/environment/cmdLineArgs.html to find out how to pass it properly.
Okay, so I have to Write a program to create a file named Lab13.txt. Write ten integers ranging [0, 99] created randomly into the file using text I/O. Integers are separated by spaces in the file. Read the data back from the file and display them on the console.
I've done this part already, but next I have to take those numbers in that file, create a new file, multiply all the numbers in the Lab13.txt file, and store them in the new file. My problem is when i create the new file, I'm only able to get it to multiply the last number printed from the Lab13.txt file. How do i get it to multiply all the numbers in Lab13.txt file by 10 and print them? This is probably a really simple solution and I feel so dumb for not being able to figure it out. Creating files is the new thing we're learning and my teacher is little to no help. :(
import java.io.*;
public class Lab13 {
public static void main(String ar[]) {
String toWrite = "";
int x=0;
try {
File file=new File("Lab13.txt");
FileWriter filewriter=new FileWriter(file);
BufferedWriter writer=new BufferedWriter(filewriter);
for(int i=0;i<10;i++) {
x=(int)(Math.random()*100);
writer.write(" "+x);
}
writer.close();
} catch(IOException e) {
e.printStackTrace();
}
try {
File file1=new File("Lab13.txt");
FileReader filereader=new FileReader(file1);
BufferedReader reader=new BufferedReader(filereader);
String y;
while((y=reader.readLine())!=null) {
System.out.println(y);
toWrite += ("" + x*10);
System.out.println(toWrite);
}
File output = new File("lab13_scale.txt");
if(!output.exists()) output.createNewFile();
FileWriter writer = new FileWriter(output.getAbsoluteFile());
BufferedWriter bWriter= new BufferedWriter(writer);
bWriter.write(toWrite);
bWriter.close();
} catch(Exception e) {
e.printStackTrace();
}
}
}
You're never reading individual numbers from that line. And the x you multiplied with 10 was the last number you randomly generated in previous loop. That's why the problem.
Remove line -
toWrite += ("" + x*10);
Replace with -
String numArray = y.split(" ");
for (int i=0; i<numArray.length; i++) {
int newNum = Integer.parseInt(numArray[i]) * 10;
toWrite += ("" + newNum);
}
Your problem is here:
while((y=reader.readLine())!=null) {
System.out.println(y);
toWrite += ("" + x*10);
System.out.println(toWrite);
}
What reader.readLine() tells the reader to do is look for every newline character "\n" and process the chunks of text in between, and since you didnt add any, it treats the whole file as a single chunk.
What you can do instead is read the entire contents of the file into a string and then split it with the space delimiter (below is untested code):
String s = reader.readLine();
String[] allNumbers = s.split(" ");
for(String number : allNumbers) {
int currentNumber = Integer.parseInt(number);
bWriter.write(String.valueOf(currentNumber * 10) + " ");
}
public void multiply() throws Exception{
//reading from existing file
BufferedReader br = new BufferedReader(new FileReader("Lab13.txt"));
String l = br.readLine(); //assuming from your code that there is only one line
br.flush();
br.close();
String[] arr = l.split(" ");
//writing into new_file.txt
BufferedWriter bw = new BufferedWriter(new FileWriter("new_file.txt"));
for(String a : arr){
bw.write((Integer.parseInt(a)*10) + " ");
}
bw.flush();
bw.close();
}
Just call this method. Should work. You basically need to split the String using space. once that done, parsing each String into Integer and multiplying. and again storing.
package com.test;
import java.io.*;
public class Lab13
{
public static void main(String ar[])
{
String toWrite = "";
int x = 0;
try
{
File file = new File("Lab13.txt");
FileWriter filewriter = new FileWriter(file);
BufferedWriter writer = new BufferedWriter(filewriter);
for (int i = 0; i < 10; i++)
{
x = (int) (Math.random() * 100);
writer.write(" " + x);
}
writer.close();
} catch (IOException e)
{
e.printStackTrace();
}
try
{
File file1 = new File("Lab13.txt");
FileReader filereader = new FileReader(file1);
BufferedReader reader = new BufferedReader(filereader);
String y;
while ((y = reader.readLine()) != null)
{
////////////////////////////////////////
//trim - delete leading spaces from y
String[] array = y.trim().split(" ");
for (int i = 0; i < array.length; i++)
{
int number = Integer.parseInt(array[i]);
System.out.println(number);
toWrite += (number * 10 + " ");
}
System.out.println(toWrite);
////////////////////////////////////////
}
File output = new File("lab13_scale.txt");
if (!output.exists()) output.createNewFile();
FileWriter writer = new FileWriter(output.getAbsoluteFile());
BufferedWriter bWriter = new BufferedWriter(writer);
bWriter.write(toWrite);
bWriter.close();
} catch (Exception e)
{
e.printStackTrace();
}
}
}
I am almost complete making this app in Eclipse. It is an android app that reads double data values from the text files in the asset directory for my app project. It stores the data values in the array, and I just need to write the square root of the double data values to the output files. I used the adb shell in the Command Prompt, and it shows the data values, but they are not in square root. The data values are still in their original double form. So, I think something must be wrong with the writing part of the code or the method that does the square root. I really don't know about Java, so please explain to me in a very simpler way. Here is the code:
public void srAndSave(View view)
{
EditText edt1;
EditText edt2;
TextView tv;
String infilename;
String outfilename;
tv = (TextView) findViewById(R.id.text_status);
//Get the name of the input file and output file
edt1 = (EditText) findViewById(R.id.edit_infile);
edt2 = (EditText) findViewById(R.id.edit_outfile);
infilename = edt1.getText().toString();
outfilename = edt2.getText().toString();
//Create an array that stores double values (up to 20)
double double_nums[] = new double[20];
int n = 0;//For storing the number of data values in the array
//Open the data file from the asset directory
//and make sure the data file exists
AssetManager assetManager = getAssets();
try
{
Scanner fsc = new Scanner(assetManager.open(infilename));
//Get the data values from the file
//and store them in the array double_nums
n = 0;
while(fsc.hasNext()){
double_nums[n] = fsc.nextDouble();
n++;
}
//Calls on square_root_it method
square_root_it(double_nums, n);
//Display that the file has been opened
tv.setText("Opening the input file and reading the file were "
+ " successful.");
fsc.close();
}
catch(IOException e)
{
tv.setText("Error: File " + infilename + " does not exist");
}
//Write the data to the output file and
//also make sure that the existence of the file
File outfile = new File(getExternalFilesDir(null), outfilename);
try
{
FileWriter fw = new FileWriter(outfile);
BufferedWriter bw = new BufferedWriter(fw);
PrintWriter pw = new PrintWriter(bw);
int x;
for(x=0;x < n;x++)
pw.println(double_nums[x]);
pw.close();
}
catch(IOException e)
{
System.out.println("Error! Output file does already exist! You will overwrite"
+ " this file!");
}
} //end srAndSave
public static void square_root_it(double[] a, int num_items)
{
int i;
for(i=0; i < num_items; i++)
Math.sqrt(a[i]);
} //end square_root_it
}
your problem is here:
for(i=0; i < num_items; i++)
Math.sqrt(a[i]);
Math.sqrt(num) returns a value, it does not set the value.
what I would do is create a second array to hold the results and then do:
for(i=0; i < num_items; i++)
results[i] = Math.sqrt(a[i]);
I'm programming a conversion tool that should take a json file as an input. Due to the problem that json input files may be very large I'll perform a split at the beginning. I have to resort the structure of the input file and because I don't want to keep the whole large file in my memory all the time, I'll split it.
I'm proofing the occurences of a json block by counting the { and }. If the counter is 0, a split should be performed. That's where the problem is: if the file is about 40MBs large the JVM throws a StackOverFlowError and I don't know why.
Here's what I do to perform a split:
/*
* Utility-function to read a json file part by part and save the parts to a separate json file.
* #param scanner The scanner which contains the file and which returns the lines from the file.
* #param j The counter of the file. As the file should change whenever the counter changes.
* #return jsonString The content of the jsonString.
*/
public String readPartOfFileAndSave(String filepath, Scanner scanner, int j) {
String jsonString = "";
int i = 0;
++j;
while (scanner.hasNext()) {
String token = scanner.next();
jsonString += token + System.lineSeparator();
if (token.contains("{")) {
i++;
}
if (token.contains("}")) {
i--;
}
if (i == 0) {
// DEBUG
// if (j % 1000 == 0) {
// System.gc();
// System.out.println("Garbage Collector called manually");
// }
saveFile(filepath, "actor", j, jsonString);
readPartOfFileAndSave(filepath, scanner, j);
}
}
return "";
}
/*
* #param filename The name of the target file where the content is saved to.
* #param j The counter of the file. As the file should change whenever the counter changes.
* #param content The content of the file.
*/
public void saveFile(String filepath, String fileprefix, int j, String content) {
File file = null;
if (this.osValidator.isWindows()) {
file = new File(filepath + "\\" + fileprefix + "" + j + ".json");
} else {
file = new File(filepath + "/" + fileprefix + "" + j + ".json");
}
try {
// if file doesnt exists, then create it
if (!file.exists()) {
file.createNewFile();
}
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file.getAbsoluteFile()), "UTF-8"));
bw.write(content);
bw.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
The exception looks like this:
Exception in thread "AWT-EventQueue-0" java.lang.StackOverflowError
at java.util.Hashtable.get(Hashtable.java:363)
at java.util.Properties.getProperty(Properties.java:969)
at java.lang.System.getProperty(System.java:717)
at sun.security.action.GetPropertyAction.run(GetPropertyAction.java:84)
at sun.security.action.GetPropertyAction.run(GetPropertyAction.java:49)
at java.security.AccessController.doPrivileged(Native Method)
at java.io.BufferedWriter.<init>(BufferedWriter.java:109)
at java.io.BufferedWriter.<init>(BufferedWriter.java:88)
at utility.ReadFileAndSave.saveFile(ReadFileAndSave.java:183)
at utility.ReadFileAndSave.readPartOfFileAndSave(ReadFileAndSave.java:158)
at utility.ReadFileAndSave.readPartOfFileAndSave(ReadFileAndSave.java:159)
splitFile() is called in a separate class. But nothing else happens there.
public void splitFile() {
try {
ReadFileAndSave reader = new ReadFileAndSave();
String jsonFilePath = this.converterView.sourceTextField.getText();
File jsonFile = new File(jsonFilePath);
Scanner scanner = new Scanner(new FileInputStream(jsonFile), "UTF-8");
int j = 0;
File newDir = null;
if (this.osValidator.isWindows()) {
newDir = new File(System.getProperty("user.home") + "\\temp\\");
} else {
newDir = new File(System.getProperty("user.home") + "/temp/");
}
if (!newDir.exists()) {
newDir.mkdir();
}
if (this.osValidator.isWindows()) {
reader.readPartOfFileAndSave(System.getProperty("user.home") + "\\temp\\", scanner, j);
} else {
reader.readPartOfFileAndSave(System.getProperty("user.home") + "/temp/", scanner, j);
}
} catch (FileNotFoundException ex) {
Logger.getLogger(FilterController.class.getName()).log(Level.SEVERE, null, ex);
}
}
The input file has about 38.000 blocks in it. About 5.200 will be splitted to separate files. Then the exception is thrown.
The JVM seems to have a problem with the BufferedWriter. Does anyone know how to fix this issue?
I'm working on a project that takes in criteria supplied by a user, and compares it to an already created list of object containing similar criteria.
Currently, I'm trying to get the program to read the file, but I keep getting my exception and not what I want. My code for the scanner and file is as followed:
package project205;
import java.util.*;
import java.io.File;
import java.util.Scanner;
import java.io.FileNotFoundException;
public class HouseList {
ArrayList<House> houseList = new ArrayList<House>();
public HouseList(String fileName)
{
//Open the data file
Scanner myFileIn = null;
try
{
myFileIn = new Scanner(new File("houses.txt"));
}
catch (FileNotFoundException e)
{
System.out.println("File: " + "houses.txt" + " is not found");
}
// First piece of data is the number of records
int numRecords = myFileIn.nextInt();
String address1;
int price1;
int area1;
int numBedroom1;
// Temp variable to accumulate the sum
//double sum = 0.0;
//Read the data line by line and build the
//array lists containing names and incomes
for (int k = 0; k < numRecords; k++)
{
address1 = myFileIn.next();
price1 = myFileIn.nextInt();
area1 = myFileIn.nextInt();
numBedroom1 = myFileIn.nextInt();
House house1 = new House(address1, price1, area1, numBedroom1);
houseList.add(house1);
}
// Close the input file
myFileIn.close();
}
public String getHouses(Criteria c)
{
String result = "";
for(int i = 0; i < houseList.size(); i++)
{
House h1 = houseList.get(i);
if (h1.satisfies(c))
{
result = result + h1.toString();
}
}
return result;
}
public void printHouses(Criteria c)
{
System.out.println(getHouses(c));
}
}
My file is in the same package, as I am using eclipse, but I keep getting "File: houses.txt is not found". To be thourough, the error I get is :
File: houses.txt is not found
Exception in thread "main" java.lang.NullPointerException
at project205.HouseList.<init>(HouseList.java:29)
at project205.HouseListTester.main(HouseListTester.java:7)
If anyone could even point me in the direction of what I'm missing here I would greatly appreciate it!
This may help you:
//creating File instance to reference text file in Java
File text = new File("<file location>/houses.txt");
//Creating Scanner instnace to read File in Java
Scanner scnr = new Scanner(text);
//Reading each line of file using Scanner class
while(scnr.hasNextLine()){
//process file
}
Use
System.getProperty("user.dir") + System.getProperty("file.separator") + "houses.txt"
to get the file path if houses.txt and the class file from which you are trying to access shares the same directory.
you can modify
myFileIn = new Scanner(new File("houses.txt"));
//to
myFileIn = new Scanner(new File(System.getProperty("user.dir") + System.getProperty("file.separator") + "houses.txt"));
//or
myFileIn = new Scanner(new File(System.getProperty("file.separator") + "houses.txt"));
Other case is that the file is in some other directory. In this scenario, provide relative path of this file ex.
//current dir is c: and your file is in d: then do
myFileIn = new Scanner(new File("addRelativeFilePathHere" + "houses.txt"));
Above, you need to end addRelativeFilePathHere with file.separator or prefix houses.txt with file separator.
This link to see what these properties points to and their meanings and for more inormation
http://docs.oracle.com/javase/tutorial/essential/io/pathOps.html and
http://docs.oracle.com/javase/7/docs/api/java/io/File.html