This document discusses file processing in Java. It covers topics like creating File objects, reading and writing files with Scanners and PrintWriters, handling exceptions when reading files, and processing file input line by line or token by token. Examples are provided to demonstrate reading numeric data from files and calculating values based on the data. The key aspects are using Scanners to read files, handling exceptions, and choosing between line-based and token-based processing depending on the file format.
The document discusses file input and output in Java. It covers the File class, opening files for reading using a Scanner, handling exceptions, reading data line-by-line and tokenizing the lines. It also discusses opening files for writing using a PrintWriter and outputting data to files. The key topics are file I/O, exception handling, and using Scanners and PrintWriters to read from and write to files in Java.
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.StringTokenizer;
/**
* Read a .dat file and reverse it.
* CPS 350
*/
public class Reverse {
public static void main(String[]args) {
if (args.length != 3) {
System.err.println(" Incorrect number of arguments");
System.err.println(" Usage: ");
System.err.
println("\tjava Reverse <stack type> <input file> <output file>");
System.exit(1);
}
boolean useList = true;
if (args[0].compareTo("list")==0)
useList = true;
else if (args[0].compareTo("array")==0)
useList = false;
else {
System.err.println("\tSaw "+args[0]+" instead of list or array as first argument");
System.exit(1);
}
try {
//
// Set up the input file to read, and the output file to write to
//
BufferedReader fileIn =
new BufferedReader(new FileReader(args[1]));
PrintWriter fileOut =
new PrintWriter(new
BufferedWriter(new FileWriter(args[2])));
//
// Read the first line of the .dat file to get sample rate.
// We want to store the sample rate value in a variable,
// but we can ignore the "; Sample Rate" part of the line.
// Step through the first line one token (word) at a time
// using the StringTokenizer. The fourth token is the one
// we want (the sample rate).
//
StringTokenizer str;
String oneLine;
int sampleRate;
String strJunk;
oneLine = fileIn.readLine();
str = new StringTokenizer(oneLine);
strJunk = str.nextToken(); // Read in semicolon
strJunk = str.nextToken(); // Read in "Sample"
strJunk = str.nextToken(); // Read in "Rate"
// Read in sample rate
sampleRate = Integer.parseInt(str.nextToken());
//
// Read in the remainder of the file on line at a time.
// The values in the first column are thrown away.
// Place values from the second column on the stack.
// Stop reading if we reach the end of the file.
//
DStack s;
if (useList)
s = new ListStack();
else
s = new ArrayStack();
String timestep;
double data;
int count = 0;
while ((oneLine = fileIn.readLine()) != null) {
if (oneLine.charAt(0) == ';') {
continue;
}
str = new StringTokenizer(oneLine);
// Read in time step value from first col.
This document discusses Java input/output (IO) streams and serialization. It covers reading and writing text and binary files using classes like FileReader, FileWriter, ObjectInputStream and ObjectOutputStream. It also discusses reading from the keyboard, reading file attributes, serialization which converts an object to bytes, deserialization which converts bytes to an object, and using the Externalizable interface to customize serialization. The goal is to provide an overview of performing IO operations and serialization in Java.
This document summarizes and compares several programming languages - C#, Visual Basic, F#, C++/CLI, and the common intermediate language (CIL) - by providing concise code examples and explanations of each language.
Core Java Programming Language (JSE) : Chapter XI - Console I/O and File I/OWebStackAcademy
This document discusses console and file input/output in Java. It describes how to read from standard input using System.in, write to standard output using System.out, and read/write files using File and FileReader/FileWriter classes. Methods for formatted output/input are also covered. The document provides examples for reading keyboard input, writing to console, and reading/writing files line-by-line.
The document summarizes a file operator project that analyzes the performance of different file operation algorithms. It describes several Python files used in the project, including the main fileop.py file that handles preprocessing and calculates averages and complexities of commands like mkdir, rmdir, read, and write. It also details the process of building the initial input.py file to compute command averages, backup.py file to store output values, and fileop.py file to determine baseline averages from a separate file and preprocess data.
PAGE 1Input output for a file tutorialStreams and File IOI.docxalfred4lewis58146
PAGE
1Input output for a file tutorialStreams and File I/O
In this tutorial we study the following concepts:
Text File I/O
Techniques for a file: Class File
Binary File I/O
File Objects and File Name
Note: For question 4 of the midterm you only need to look at the sections 2.2 and 2.3. I do not think you need java class: StringTokenizer. But I just added a small section about it to the end of this tutorial.
So far we learned keyboard/screen I/O. It is time to learn File I/O.
1 An Overview of stream and file I/O
A stream is an object that either outputs data or inputs data. The Java System.out is a stream object that outputs data on the screen.
As our program gets bigger and bigger we may need to enter a lot of data every time we run our program. We also may have a lot of data as the output of the program. It is not practical to enter a sizable input from the keyboard. Therefore, we save the data in a file and let our program to input from this file. Similarly, it is not practical to look at a sizable output. Moreover, we may need to save the output for further study. Therefore, we let our program to output to a file.
We have two kinds of I/O files: Text files and binary files. A text file is readable and understandable by human, but a binary file is not. The size of a text file is bigger than the size of a binary file. We can write arrays without using a loop into a binary file. We can also write objects to a binary file.
2 Text-File I/O
In this section we learn how to input from a text file and how to output to a text file. We first look at output instructions for a text file.
2.1 Text-File Output with PrintWriter class.
To be able to write to a file we need the Java class PrintWriter. This class is in JDK java.io, therefore we need to import it . Another class that we need is : FileOutputStream. This class also is in java.io. A file output stream is an output stream for writing data to a File.
Example 1. The following program to write an integer, a floating point number, a Boolean value and a string into a text file.
import java. io. PrintWriter;
import java. io. FileNotFoundException;
publicclass Main {
publicstaticvoid main( String[] args) {
PrintWriter out = null;
try {
out = new PrintWriter("out.txt");
} catch( FileNotFoundException e) {
System. out. println("Error: opening the file out.txt");
System. exit( 0);
}
out.println(-12);
out.println(25.5);
out.println(true);
out.println("John Doe.");
//Note that we also can write:
out.println(-12+"\n"+ 25.5 + "\n" + true + "\n" + "John Doe.");
out.close();
} }
The content of the file out.txt would be:
-12
25.5
true
John Doe.
-12
25.5
true
John Doe.
Description:
First we need to declare a variable that refers to and object of class PrintWriter. This class has several constructors. One of them needs the name of the output file on the hard drive (or other storages): out = new PrintWriter("out.txt")
This instruction co.
Exceptions, I/O and Threads Input and Output in Java: The File Class, Standard Streams, Keyboard
Input, File I/O Using Byte Streams, Character Streams, File I/O Using Character Streams -
Buffered Streams, File I/O Using a Buffered Stream, Keyboard Input Using a Buffered Stream,Writing Text Files. Threads: Threads vs. Processes, Creating Threads by Extending Thread,
Creating Threads by Implementing Runnable, Advantages of Using Threads, Daemon Threads,
Thread States, Thread Problems, Synchronization. Exceptions: Exception Handling, The Exception
Hierarchy, throws statement, throw statement, Developing user defined Exception Classes- The
finally Block.
The document discusses file input and output in Java. It covers the File class, opening files for reading using a Scanner, handling exceptions, reading data line-by-line and tokenizing the lines. It also discusses opening files for writing using a PrintWriter and outputting data to files. The key topics are file I/O, exception handling, and using Scanners and PrintWriters to read from and write to files in Java.
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.StringTokenizer;
/**
* Read a .dat file and reverse it.
* CPS 350
*/
public class Reverse {
public static void main(String[]args) {
if (args.length != 3) {
System.err.println(" Incorrect number of arguments");
System.err.println(" Usage: ");
System.err.
println("\tjava Reverse <stack type> <input file> <output file>");
System.exit(1);
}
boolean useList = true;
if (args[0].compareTo("list")==0)
useList = true;
else if (args[0].compareTo("array")==0)
useList = false;
else {
System.err.println("\tSaw "+args[0]+" instead of list or array as first argument");
System.exit(1);
}
try {
//
// Set up the input file to read, and the output file to write to
//
BufferedReader fileIn =
new BufferedReader(new FileReader(args[1]));
PrintWriter fileOut =
new PrintWriter(new
BufferedWriter(new FileWriter(args[2])));
//
// Read the first line of the .dat file to get sample rate.
// We want to store the sample rate value in a variable,
// but we can ignore the "; Sample Rate" part of the line.
// Step through the first line one token (word) at a time
// using the StringTokenizer. The fourth token is the one
// we want (the sample rate).
//
StringTokenizer str;
String oneLine;
int sampleRate;
String strJunk;
oneLine = fileIn.readLine();
str = new StringTokenizer(oneLine);
strJunk = str.nextToken(); // Read in semicolon
strJunk = str.nextToken(); // Read in "Sample"
strJunk = str.nextToken(); // Read in "Rate"
// Read in sample rate
sampleRate = Integer.parseInt(str.nextToken());
//
// Read in the remainder of the file on line at a time.
// The values in the first column are thrown away.
// Place values from the second column on the stack.
// Stop reading if we reach the end of the file.
//
DStack s;
if (useList)
s = new ListStack();
else
s = new ArrayStack();
String timestep;
double data;
int count = 0;
while ((oneLine = fileIn.readLine()) != null) {
if (oneLine.charAt(0) == ';') {
continue;
}
str = new StringTokenizer(oneLine);
// Read in time step value from first col.
This document discusses Java input/output (IO) streams and serialization. It covers reading and writing text and binary files using classes like FileReader, FileWriter, ObjectInputStream and ObjectOutputStream. It also discusses reading from the keyboard, reading file attributes, serialization which converts an object to bytes, deserialization which converts bytes to an object, and using the Externalizable interface to customize serialization. The goal is to provide an overview of performing IO operations and serialization in Java.
This document summarizes and compares several programming languages - C#, Visual Basic, F#, C++/CLI, and the common intermediate language (CIL) - by providing concise code examples and explanations of each language.
Core Java Programming Language (JSE) : Chapter XI - Console I/O and File I/OWebStackAcademy
This document discusses console and file input/output in Java. It describes how to read from standard input using System.in, write to standard output using System.out, and read/write files using File and FileReader/FileWriter classes. Methods for formatted output/input are also covered. The document provides examples for reading keyboard input, writing to console, and reading/writing files line-by-line.
The document summarizes a file operator project that analyzes the performance of different file operation algorithms. It describes several Python files used in the project, including the main fileop.py file that handles preprocessing and calculates averages and complexities of commands like mkdir, rmdir, read, and write. It also details the process of building the initial input.py file to compute command averages, backup.py file to store output values, and fileop.py file to determine baseline averages from a separate file and preprocess data.
PAGE 1Input output for a file tutorialStreams and File IOI.docxalfred4lewis58146
PAGE
1Input output for a file tutorialStreams and File I/O
In this tutorial we study the following concepts:
Text File I/O
Techniques for a file: Class File
Binary File I/O
File Objects and File Name
Note: For question 4 of the midterm you only need to look at the sections 2.2 and 2.3. I do not think you need java class: StringTokenizer. But I just added a small section about it to the end of this tutorial.
So far we learned keyboard/screen I/O. It is time to learn File I/O.
1 An Overview of stream and file I/O
A stream is an object that either outputs data or inputs data. The Java System.out is a stream object that outputs data on the screen.
As our program gets bigger and bigger we may need to enter a lot of data every time we run our program. We also may have a lot of data as the output of the program. It is not practical to enter a sizable input from the keyboard. Therefore, we save the data in a file and let our program to input from this file. Similarly, it is not practical to look at a sizable output. Moreover, we may need to save the output for further study. Therefore, we let our program to output to a file.
We have two kinds of I/O files: Text files and binary files. A text file is readable and understandable by human, but a binary file is not. The size of a text file is bigger than the size of a binary file. We can write arrays without using a loop into a binary file. We can also write objects to a binary file.
2 Text-File I/O
In this section we learn how to input from a text file and how to output to a text file. We first look at output instructions for a text file.
2.1 Text-File Output with PrintWriter class.
To be able to write to a file we need the Java class PrintWriter. This class is in JDK java.io, therefore we need to import it . Another class that we need is : FileOutputStream. This class also is in java.io. A file output stream is an output stream for writing data to a File.
Example 1. The following program to write an integer, a floating point number, a Boolean value and a string into a text file.
import java. io. PrintWriter;
import java. io. FileNotFoundException;
publicclass Main {
publicstaticvoid main( String[] args) {
PrintWriter out = null;
try {
out = new PrintWriter("out.txt");
} catch( FileNotFoundException e) {
System. out. println("Error: opening the file out.txt");
System. exit( 0);
}
out.println(-12);
out.println(25.5);
out.println(true);
out.println("John Doe.");
//Note that we also can write:
out.println(-12+"\n"+ 25.5 + "\n" + true + "\n" + "John Doe.");
out.close();
} }
The content of the file out.txt would be:
-12
25.5
true
John Doe.
-12
25.5
true
John Doe.
Description:
First we need to declare a variable that refers to and object of class PrintWriter. This class has several constructors. One of them needs the name of the output file on the hard drive (or other storages): out = new PrintWriter("out.txt")
This instruction co.
Exceptions, I/O and Threads Input and Output in Java: The File Class, Standard Streams, Keyboard
Input, File I/O Using Byte Streams, Character Streams, File I/O Using Character Streams -
Buffered Streams, File I/O Using a Buffered Stream, Keyboard Input Using a Buffered Stream,Writing Text Files. Threads: Threads vs. Processes, Creating Threads by Extending Thread,
Creating Threads by Implementing Runnable, Advantages of Using Threads, Daemon Threads,
Thread States, Thread Problems, Synchronization. Exceptions: Exception Handling, The Exception
Hierarchy, throws statement, throw statement, Developing user defined Exception Classes- The
finally Block.
This document provides information about input and output in Java. It discusses files, streams, standard streams like System.in and System.out, and different ways of handling keyboard input in Java programs. The File class in Java represents files and directories on the disk. It describes the various File class constructors, methods, and examples of using the File class to work with files like creating, reading, and checking files. Standard streams provide predefined paths for input/output. Streams can be byte-based or character-based. Keyboard input can be handled using command line arguments, the Console class, Scanner class, or InputStreamReader class.
Hi, I need help with a java programming project. specifically practi.pdfPRATIKSINHA7304
Given 8 distinct integers from the set {1, 2, . . . , 16}, prove that there exists k such that ai aj = k
has at least 3 distinct solutions (ai , aj ) ?
Solution
For any k (unless the K is zero), at least 3 distinct solutions need not be existing.
Let\'s look at the next most favourable case
If k= 2;
We have to consider the case where the number of solutions of ai-aj=2 are minimum since we
have to show that at least 3 distinct solutions exist (which means even in the most unfavourable
case for a chosen k there will be 3 distinct solutions satisfying the equation ai-aj=2)
If k = 2; we start by taking numbers that are not at all 2 units apart from each other;
So we start with 1 and move 3 units successively ahead
1, 4, 7, 10,13, 16; Now we notice that these 6 numbers are of 3k+1 form; remaining numbers
can be any 2 ranomdly selected say 2 and 11; we get 4-2 = 2 and 13-11=2; Hence only 2 distinct
solutions are possible..
Can someone put this code in a zip file. I tried running it last tim.pdffedosys
Can someone put this code in a zip file. I tried running it last time it was answered but it did not
work.. Please and thanks in advance..
In my template for how to solve JH2, I assume you have seen the StringTokenizer which should
be covered in cps161. You can find it in the first 9 chapters of \"Absolute Java\" by Savitch. The
StringTokenizer is a simple class for parsing a String that has multiple words on it. Run the
following simple example to see what it does:
class participation: 5 points
file_operations(45 points)
Create a package named file_operations and a class named FileOperations which will receive
one or more command line pathnames to command files. Each command file will be opened and
processed line by line. Each line can contain one of the following commands:
? - This command will print out the legal commands available
createFile - The first string following \"createFile\" will be treated as a filename, and the
remaining strings will be written to the file separated by new lines.
printFile - The first string following \"printFile\" will be treated as a filename that will be opened
up and printed out to the screen.
lastModified - The first string following \"lastModified\" will be treated as a filename for which
we will print out the date when this file was last modified.
size - The first string following \"size\" will be treated as a filename for which we will print out
the number of bytes it contains.
rename - The first string following \"rename\" will be treated as the current filename and the
second string will be treated as the new filename we desire.
mkdir - The first string following \"mkdir\" will be treated as the name of a directory that should
be created.
delete - The first string following \"delete\" will be treated as the name of a file that should be
deleted.
list - The first string following \"list\" will be treated as the name of a directory for which we
want a list of the files it contains.
quit - exit program
Anything else is a bad command
For a non-existent command file, you would get something like:
For a good command file like cmd.txt
cmd.txt
Your output would look something like:
Here is a template that you can use.
Once you have your program written, I want you to add the following files to the top level of
your project and run the test that I request:
cmd1.txt
cmd2.txt
Run your program with the following command line:
cmd1.txt non-existent-file cmd2.txt
Insert the contents of your screen into the appropriate JH2 worksheet.
Please don\'t create a file with the name non-existent-file!!!
Solution
Hi,
PFB the class for the question. Please comment for any queries/feedbacks.
Thanks,
Anita
FileOperations.java
package file_operations;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.text.SimpleDat.
This document provides instructions for a lab assignment to create a C++ console application to store and retrieve contact information from a sequential text file. The program will allow the user to append new records to the file by inputting names and addresses. It will also read the records from the file and display them in a formatted output. The lab consists of 5 steps: 1) requirements for the program, 2) pseudocode for processing logic, 3) creating a new project, 4) compiling and executing the program, and 5) providing screenshots and the program code in a Word document. The goal is to build upon provided code to complete the assignment of writing, reading, and displaying records to and from a sequential text file.
For the following I have finished most of this question but am havin.pdfarihantplastictanksh
For the following I have finished most of this question but am having problem with on method. I
just need the void copyNumbers method filled out. The commented out sections describe what it
needs to do. I have it started. Just need it finished.
package reading_with_exceptions;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.PrintStream;
import java.util.InputMismatchException;
import java.util.Scanner;
public class Reading_With_Exceptions {
// 1.) Create a Scanner from the inputFilename. Catch exceptions from errors.
// 2.) Read the first String from the file and use it to create a PrintStream
// catching appropriate exceptions
// 3.) Using hasNextInt and nextInt, carefully read the count integer.
// I recommend -1 for a count value if it is bad to indicate reading ALL
// 4.) Use copyNumbers method described below to complete the job
// 5.) Close Scanner and PrintStream objects
// 6.) Call printToScreen to copy the output file to the screen
void process(String inputFilename) {
int number_to_read = 0;
try {
Scanner input = new Scanner(inputFilename);
String outputFilename = input.next();
PrintStream os = new PrintStream(new FileOutputStream(outputFilename));
if ( input.hasNextInt()) {
number_to_read = input.nextInt();
}else {
number_to_read = -1;
}
copyNumbers(input, os, number_to_read);
input.close();
os.close();
printToScreen(outputFilename);
}catch (FileNotFoundException e) {
System.out.println(\"Cannot find file: \" + e);
return;
}
}
// The following routine is called to complete the job of copying integers to
// the output file:
// scan - a Scanner object to copy integers from
// ps - A PrintStream to write the integers to
// numIntsToRead - number of integers to read. A value of -1 ==> read all integers
void copyNumbers(Scanner scan, PrintStream ps, int numIntsToRead) {
// hasNext() can be used to see if the scan object still has data
// Note that hasNextInt() can be used to see if an integer is present
// nextInt() will read an integer
// next() can be used to skip over bad integers
while (scan.hasNext()) {
if (numIntsToRead < 0) {
//print out a complaint message and then read as many integers as you find.
scan.nextInt();
}
if (!scan.hasNextInt()) {
// print a complaint message and skip over the data
scan.next();
}
if ( scan < numIntsToRead) {
// complain but do not abort
}
}
}
public static void main(String[] args) {
Reading_With_Exceptions rwe = new Reading_With_Exceptions();
for (int i=0; i < args.length; i++) {
System.out.println(\"\ \ =========== Processing \"+ args[i] + \" ==========\ \");
rwe.process(args[i]);
}
}
// For the last step, we Copy the contents of the file to the screen
private void printToScreen(String filename) {
Scanner scan = null;
try {
FileInputStream fis = new FileInputStream(filename);
scan = new Scanner(fis);
while (scan.hasNextLine()) {
System.out.println(scan.nextLine());
}
}
catch (FileNotFoundException e) {
System.out.println(\"printToS.
Task #1 Correcting Logic Errors in FormulasCopy and compile the so.pdfinfo706022
Task #1 Correcting Logic Errors in Formulas
Copy and compile the source file NumericTypes.java, run the program, and observe the output.
Some of the output is incorrect. You need to correct logic errors in the average formula and the
temperature conversion formula. The logic errors could be due to conversion between data types,
order of operations, or formula problems. The necessary formulas are
average = (score1+score2) / numberOfScores
C = 5/9 (F-32)
Make sure that the output makes sense before you continue. The average of 95 and 100 should be
97.5 and the temperature that water boils is 100 degrees Celsius
Task #2 Using the Scanner Class for User Input
1. Add an import statement above the class declaration to make the Scanner
class available to your program.
2. In the main method, create a Scanner object and connect it to the System.in
object.
3. Prompt the user to enter his or her first name.
4. Read the name from the keyboard using the nextLine method, and store it into
a variable called firstName (you will need to declare any variables you use).
5. Prompt the user to enter his or her last name.
6. Read the name from the keyboard and store it in a variable called lastName.
7. Concatenate the firstName and lastName with a space between them and
store the result in a variable called fullName.
8. Print out the fullName.
9. Compile, debug, and run, using your name as test data.
10. Since we are adding on to the same program, each time we run the program we
will get the output from the previous tasks before the output of the current task.
Task #3 Working with Strings
1. Use the charAt method to get the first character in firstName and store it in a
variable called firstInitial (you will need to declare any variables that you
use).
2. Print out the user’s first initial.
3. Use the toUpperCase method to change the fullName to uppercase and store
it back into the fullName variable.
4. Add a line that prints out the value of fullName and how many characters
(including the space) are in the string stored in fullName (use the length
method to obtain that information).
5. Compile, debug, and run. The new output added on after the output from the
previous tasks should have your initials and your full name in uppercase
characters.
Task #4 Using Predefined Math Functions
Task #4 UsingPredefined Math Functions
Add a line that prompts the user to enter the diameter of a sphere.
Read in and store the number into a variable called diameter (you will need to declare any
variables that you use).
The diameter is twice as long as the radius, so calculate and store the radius in an appropriately
named variable.
The formula for the volume of a sphere is
r3
Convert the formula to Java and add a line which calculates and stores the value of volume in an
appropriately named variable. Use Math.PI for and Math.pow to cube the radius.
Print your results to the screen with an appropriate message.
Compile, debug, and run using the following test data and record the resu.
This document provides information about the Linux boot process and basic Linux commands.
1. The Linux boot process involves six main stages: BIOS, MBR, GRUB, kernel, init, and runlevel programs. BIOS loads the MBR which loads GRUB, GRUB loads the kernel and initrd, the kernel loads init, and init executes programs based on the specified runlevel.
2. Basic Linux commands demonstrated include echo, date, cal, passwd, ls, cat, wc, cp, mv, rm, head, tail, mkdir, cd, pwd, chmod, and commands using pipes, redirection, and variables.
3. The vi editor commands demonstrated are for inserting,
Article link httpiveybusinessjournal.compublicationmanaging-.docxfredharris32
Article link: http://iveybusinessjournal.com/publication/managing-global-risk-to-seize-competitive-advantage/
Requirements: Write one summary and study note both no longer than one pages should include all point of article. Then do a PPT and write a presenting paper only for 5 minutes.
Groups of students will create and offer two MS PowerPoint presentation summarizing the main points of one of the readings for this course along with a one page handout for the students in the class. The aim of the presentations and the handouts is to provide the audience with the main ideas of the article and study notes. Groups will bring to class enough copies of the handout for each student in the class. The handout should list the name of the author, the title of the article, the title of the journal, and the publication date and page numbers along with a summary of its main points. Please do not exceed one page for this material.
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.StringTokenizer;
/**
* Read a .dat file and reverse it.
*/
public class Reverse {
public static void main(String[]args) {
if (args.length != 3) {
System.err.println(" Incorrect number of arguments");
System.err.println(" Usage: ");
System.err.
println("\tjava Reverse <stack type> <input file> <output file>");
System.exit(1);
}
boolean useList = true;
if (args[0].compareTo("list")==0)
useList = true;
else if (args[0].compareTo("array")==0)
useList = false;
else {
System.err.println("\tSaw "+args[0]+" instead of list or array as first argument");
System.exit(1);
}
try {
//
// Set up the input file to read, and the output file to write to
//
BufferedReader fileIn =
new BufferedReader(new FileReader(args[1]));
PrintWriter fileOut =
new PrintWriter(new
BufferedWriter(new FileWriter(args[2])));
//
// Read the first line of the .dat file to get sample rate.
// We want to store the sample rate value in a variable,
// but we can ignore the "; Sample Rate" part of the line.
// Step through the first line one token (word) at a time
// using the StringTokenizer. The fourth token is the one
// we want (the sample rate).
//
StringTokenizer str;
String oneLine;
int sampleRate;
String strJunk;
oneLine = fileIn.readLine();
str = new StringTokenizer(oneLine);
strJunk = str.nextToken(); // Read in semicolon
strJunk = str.nextToken(); // Read in "Sample"
strJunk = str.nextToken(); // Read in "Rate"
// ...
This document discusses file handling in C++. It explains that file handling allows storing data permanently on a computer's hard disk. The key steps for file handling are naming a file, opening it, writing data, reading data, and closing the file. It also discusses various file handling functions like fstream, ifstream, ofstream and their usage for opening, reading, writing and closing files. Functions like get(), put(), tellg(), seekg() and their usage with file streams are explained. Examples are provided to demonstrate reading from and writing to files.
The document provides examples of code snippets in C# to demonstrate various OOP concepts like inheritance, polymorphism, delegates, constructors, exception handling, file I/O, and adding a flash item to a website. It also explains XML and DTDs. The code snippets show how to implement inheritance by defining a base Shape class and derived Rectangle class, implement polymorphism by overloading a print method, use delegates to call methods, define default and parameterized constructors, handle exceptions, perform file read/write operations, and add a flash file to an HTML document. The explanation of XML covers internal and external DTD declarations to define document structure.
Reaction StatisticsBackgroundWhen collecting experimental data f.pdffashionbigchennai
Reaction Statistics
Background
When collecting experimental data from chemical reactions, it’s often useful to generate
statistics based on the data. One experimental measure is the reaction rate in moles per second,
representing the amount of product formed per unit time. If we have a set of these reaction rates
collected in a data file, we can calculate summary statistical information, such as the minimum
and maximum values, the arithmetic mean, variance, and standard deviation.
Finding the minimum and maximum are straightforward: we scan through all the data, and keep
track of the smallest and largest values encountered. The arithmetic mean (or average) is defined
as:
m = (X1+X2+…+Xn)/n
where n is the number of reaction rates, and xi represents one experimental reaction rate. Once
you have the arithmetic mean, the variance can be calculated as the mean of the squares of the
deviations from the mean:
v= ((Xn-m)^2+(X2 – m^2) + …+(Xn-m)^2)/n
where n is the number of reaction rates, xi represents one experimental reaction rate, and m is the
arithmetic mean of the reaction rates. Once you have the variance, you can calculate the
standarddeviation as:
s = sqrt(v)
Assignment
You will develop a C program that reads data from an input text file containing chemical
reaction rates (in moles per second), and computes the minimum, maximum, arithmetic mean,
variance, and standard deviation for that set of data. Your instructor will provide input text files,
which will each contain a series of double values, each on a line of its own within the file. Your
program will read one of these input files into an array of doubles (i.e., it will populate the array
using the data values from the file). Your program will then calculate statistics using that array of
doubles, and will write the results out to a separate output text file.
The goals of this assignment are to provide you with experience reading and writing text data
files, provide you with experience passing an array into a function, and give you more
experience organizing your program into separate C functions.
When defining your C functions, you may either:
Define the functions before they are used by any other functions, OR
Place function prototypes near the top of your code (after all #include directives), and then define
the functions in any order.
Part 1 – Opening Files and Reading Data
Create a new Visual Studio Win32 Console project named reactionstats. Create a new C source
file named project4.c within that project. At the top of the source file, #define
_CRT_SECURE_NO_WARNINGS, and then include stdio.h, math.h, stdlib.h, stdbool.h, and
float.h.
Inside your main function, define the following:
A one-dimensional array of 600 doubles. They do not need to be initialized to anything at this
stage.
An integer variable to hold the number of elements in the array, initialized using the approach
demonstrated in class, using sizeof.
A FILE pointer variable, which will refer to the input data text file..
This presentation comes with many additional notes (pdf): http://de.slideshare.net/nicolayludwig/2-c-sharp-introductionbasicsparti-38639098
- A Tour through other .Net Programming Languages
- C# Syntax Cornerstones
1-Information sharing
2-Computation speedup
3-Modularity
4-Convenience
5-allows exchanged data and informations
Two IPC Models
1. Shared memory- is an OS provided abstraction which allows a memory region to be simultaneously accessed by multiple programs with an intent to provide communication among them. One process will create an area in RAM which other processes can accessed
2. Message passing - is a form of communication used in interprocess communication. Communication is made by the sending of messages to recipients. Each process should be able to name the other processes. The producer typically uses send() system call to send messages, and the consumer uses receive()system call to receive messages
Shared memory
Faster than message passing
After establishing shared memory, treated as routine memory accesses
Message passing
Useful for exchanging smaller amounts of data
Easy to implement, but more time-consuming task of kernel intervention
Bounded-Buffer Problem Producer Process
do {
...
produce an item in nextp
...
wait(empty);
wait(mutex);
...
add nextp to buffer
...
signal(mutex);
signal(full);
} while (true);
Bounded-Buffer Problem Consumer Process
do {
wait(full);
wait(mutex);
...
remove an item from buffer to nextc
...
signal(mutex);
signal(empty);
...
consume the item in nextc
...
} while (true);
client-server model, the client sends out requests to the server, and the server does some processing with the request(s) received, and returns a reply (or replies)to the client.
Since Socket can be described as end-points for communication. we could imagine the client and server hosts being connected by a pipe through which data-flow takes place.
1-sockets use a client-server while Server waits for incoming client requests by listening to a specified port.
2-After receiving a request, the server accepts a connection from the client socket to complete the connection
3-then Remote procedure call (RPC) abstracts procedure call mechanism for use between systems with network connections
4-and pipes acts as a conduit allowing two processes to communicate
A process is different than a program
- Program is static code and static data
- Process is Dynamic instance of code and data
-Program becomes process when executable file loaded into memory
No one-to-one mapping between programs and processes
-can have multiple processes of the same program
-one program can invoke multiple process
Execution of program started via GUI mouse clicks and command line entry of its name
The process state transition
As a process executes, The process is being created, then The process is waiting to be assigned to a processor therefore, Instructions are being executed then The process is waiting for some event to occur,thereafter The process has finished exec ...
You have been hired by Planet Poachers to write a Java console appli.pdfamitbagga0808
You have been hired by Planet Poachers to write a Java console application that reads, converts,
sorts, and writes planet data. Create text file PlanetDataEnglish.txt, paste the following data into
it, and place the file in your project folder.
PlanetDataEnglish.txt
Planet Escape Velocity (miles/s) Mean Temperature (F) Number of Moons
Mercury 2.7 333 0
Venus 6.4 867 0
Earth 7.0 59 1
Mars 3.1 -85 2
Jupiter 37.0 -166 67
Saturn 22.1 -220 62
Uranus 13.2 -320 27
Neptune 14.6 -330 13
Pluto 0.7 -375 5
Create the following methods:
Column Purpose
readTextFile To read the data from file PlanetDataEnglish.txt into four parallel arrays: planets,
escapes, means, and moons.
printArrays To print the unsorted, converted, and sorted data using the appropriate column
headers.
convertArrays To convert the escape velocities from miles/s to km/s, and to convert the mean
temperatures from Fahrenheit to Celsius.
bubbleSortArray To sort the data by planet name in ascending order. Note that when values are
swapped in one array, the same values must be swapped in the other arrays.
writeTextFile To write the data to file PlanetDataMetric.txt in the same layout as the input file.
Sample Output on .txt file
PlanetDataMetric.txt
Planet Escape Velocity (miles/s) Mean Temperature (F) Number of Moons
Earth 11.3 15 1
Jupiter 59.5 -110 67 …
Solution
Following will be program for the planet as requested
//Inclusion of the lib files
Import Java.util.scanner;
import java.io.Filewriter;
import java.io.PrintWriter;
Import java.io.FileNotFoundException;
import java.util.InputMismatchException;
import java.io.IOException;
import java.io.File;
Public class Planets // Main method is followed
{
public static void main(String[] args) // main mehtod
{
// variables are declared
scanner keyboard = new Scanner(System.in); // here the keyboard will be connected
Scanner fileIn = null; //file variable are declared
String fileInName = \"PlanetSourceData.txt\";// File name variable is declared
int i=0;
int j=0;
int k =0;
int Usednumber = 10;
String [] Plantets = new String[20];
int [] diameters = new int[15];
double [] leng = newdouble [12];
try
{
fileIn = new Scanner(new FileInputStream(fileInName)); //Scanning of the text file is done
}
Catch(FileNotFoundException e) \\\\catching of the exception
{
System.out.printIn(\"Error:File \'\" +fileInName+ \"\' not found.\"); //gives the error message that
file is not found
System.exit(-1);
}
System.out.println(\"This is templelate from Java keyboard entry\");
// To read the input file this loop is formed
while(fieIn.hasNextLine())
{
Planets[i] = fileIn.next();
diameters[j] = fileIn.nextInt();
lengths[k] = fileIn.nextDouble();
System.out.Printf(\"%-10 %8s %8s %n\" , \"Planets\", \"Diameter(miles)\",\" Hours of the
planest(Length of the planet:);
System.out.printf(\"%-10s %8d %8.1f 5n \", planets[i], diameters[j] , lenths [k]);
}
PrintArray(diameters, numberUsed);
bubbleSortArray(diameters,numberUsed); //finding the miles(escape velocity)
printArray(dua.
Here are the key points about defining a class in Python:
- A class is defined using the class keyword.
- The class name starts with a capital letter by convention.
- Attributes are defined inside the class but outside any methods. These are like variables that belong to the class.
- Methods are defined inside the class and are functions defined to perform operations on the class objects.
- The __init__() method is called automatically whenever a new object is instantiated. It is used to initialize the attributes of the object.
- To create an object of the class, the class name is used as a function. This returns a new instance of the class.
So in summary, a class groups
Penetrating Windows 8 with syringe utilityIOSR Journals
This document discusses penetrating Windows 8 remotely using Metasploit framework and syringe utility. It begins with an introduction to penetration testing and Windows 8 security. It then describes using Metasploit to generate a payload, encoding it to evade detection, and injecting it into a Windows 8 system using syringe. This allows establishing a meterpreter session and compromising the system by migrating processes and accessing the C drive. It concludes that Windows 8 has strong security but syringe injections allow compromising it, and more exploits could be found to enhance efficacy.
The document outlines the schedule and objectives for an operating systems lab course over 10 weeks. The first few weeks focus on writing programs using Unix system calls like fork, exec, wait. Later weeks involve implementing I/O system calls, simulating commands like ls and grep, and scheduling algorithms like FCFS, SJF, priority and round robin. Students are asked to display Gantt charts, compute waiting times and turnaround times for each algorithm. The final weeks cover inter-process communication, the producer-consumer problem, and memory management techniques.
The document discusses data files in Visual Basic. It provides 12 questions with explanations about key concepts related to data files, including:
1) The difference between a VB project file and data file is that a project file contains code modules while a data file stores information on the hard disk in records with fields.
2) The open statement reserves a file handle (channel) to read from and write to a file, associating a number to the handle for later access.
3) Common file modes are input, output, append, and random for different types of file access.
4) A file number maintains files in a project and is used instead of file names for reference.
Description 1) Create a Lab2 folder for this project2.docxtheodorelove43763
Description
1) Create a Lab2 folder for this project
2) Use the main driver program (called Writers.java) that I provide below to write files of differing types. You can copy and paste this code, but make sure the spaces variable copies correctly. The copy and paste operation eliminates the spaces between the quotes on some systems.
3) In the writers program, fill in the code for the three classes (Random, Binary, and Text). In each class, you will need a constructor, a write method, and a close method. The constructor opens the file, the write method writes a record, and the close method closes the file.
4) Other than what I just described, don't change the program in any way. The program asks for a file type (random, binary, or text) and the name of the file to create. In a loop it inputs a person's name (string), a person's age (int), and a person's annual salary (double). It writes to a file of the appropriate type. The loop terminates when the user indicates that inputting is complete. The program then asks if another file should be created. If the answer is yes, the whole process starts again. This and all of the java driver programs should be saved in your lab2 folder but not in the cs258 sub-folder.
5) Note: The method signatures for accessing all of the three types of files (binary, random, and text) are on the class web-site. Go to power point slides and click on week two. This will help if you didn't take accurate notes in class.
6) Write a main program to read binary files (BinReader.java). This program only needs to be able to read and display records from a Binary file that was created by the writers program.
7) Write a main program to read random files (RandReader.java). This program only needs to be able to read and display records from a Binary file that was created by the writers program. Make sure that this program reads and displays records in reverse order. DO NOT USE AN ARRAY!!!
8) In your Lab2 folder, create a subfolder within lab2 named cs258. Download Keyboard.java from the class web-site to that folder. Add a new first line of Keyboard.java with the statement, package cs258;. This line will make Keyboard.java part of the cs258 package. The driver program shown below has an import ‘cs258.*;’ statement to access the java files in this package.
9) Modify Keyboard.java. We want to extend this class so it can be extended to allow access to multiple files. The changes follow:
a. Remove all static references. This is necessary so that there will be an input stream variable (in) in each object.
b. Change the private modifier of the in and current_token variables to protected. Change the private modifier to protected in all of the signature lines of the overloaded getNextToken methods.
c. Create a constructor that instantiates the input stream for keyboard input. Remove the instantiation from the original declaration line for the in variable. The constructor doesn't need any parameters.
10)Create a class TextR.
This document provides an overview of arrays in Java, including how to declare, initialize, access, and manipulate array elements. It discusses key array concepts like indexes, the length field, and for loops for traversing arrays. Examples are provided for common array operations like initialization, accessing elements, and passing arrays as parameters or returning them from methods. Limitations of arrays are also covered.
The document discusses different types of loops in Java including while loops, do-while loops, and indefinite loops using sentinels. It provides examples of using random numbers and boolean return values from methods to implement program logic within loops. Key concepts covered include fencepost problems, random number generation, and using boolean values to represent logical tests.
This document provides information about input and output in Java. It discusses files, streams, standard streams like System.in and System.out, and different ways of handling keyboard input in Java programs. The File class in Java represents files and directories on the disk. It describes the various File class constructors, methods, and examples of using the File class to work with files like creating, reading, and checking files. Standard streams provide predefined paths for input/output. Streams can be byte-based or character-based. Keyboard input can be handled using command line arguments, the Console class, Scanner class, or InputStreamReader class.
Hi, I need help with a java programming project. specifically practi.pdfPRATIKSINHA7304
Given 8 distinct integers from the set {1, 2, . . . , 16}, prove that there exists k such that ai aj = k
has at least 3 distinct solutions (ai , aj ) ?
Solution
For any k (unless the K is zero), at least 3 distinct solutions need not be existing.
Let\'s look at the next most favourable case
If k= 2;
We have to consider the case where the number of solutions of ai-aj=2 are minimum since we
have to show that at least 3 distinct solutions exist (which means even in the most unfavourable
case for a chosen k there will be 3 distinct solutions satisfying the equation ai-aj=2)
If k = 2; we start by taking numbers that are not at all 2 units apart from each other;
So we start with 1 and move 3 units successively ahead
1, 4, 7, 10,13, 16; Now we notice that these 6 numbers are of 3k+1 form; remaining numbers
can be any 2 ranomdly selected say 2 and 11; we get 4-2 = 2 and 13-11=2; Hence only 2 distinct
solutions are possible..
Can someone put this code in a zip file. I tried running it last tim.pdffedosys
Can someone put this code in a zip file. I tried running it last time it was answered but it did not
work.. Please and thanks in advance..
In my template for how to solve JH2, I assume you have seen the StringTokenizer which should
be covered in cps161. You can find it in the first 9 chapters of \"Absolute Java\" by Savitch. The
StringTokenizer is a simple class for parsing a String that has multiple words on it. Run the
following simple example to see what it does:
class participation: 5 points
file_operations(45 points)
Create a package named file_operations and a class named FileOperations which will receive
one or more command line pathnames to command files. Each command file will be opened and
processed line by line. Each line can contain one of the following commands:
? - This command will print out the legal commands available
createFile - The first string following \"createFile\" will be treated as a filename, and the
remaining strings will be written to the file separated by new lines.
printFile - The first string following \"printFile\" will be treated as a filename that will be opened
up and printed out to the screen.
lastModified - The first string following \"lastModified\" will be treated as a filename for which
we will print out the date when this file was last modified.
size - The first string following \"size\" will be treated as a filename for which we will print out
the number of bytes it contains.
rename - The first string following \"rename\" will be treated as the current filename and the
second string will be treated as the new filename we desire.
mkdir - The first string following \"mkdir\" will be treated as the name of a directory that should
be created.
delete - The first string following \"delete\" will be treated as the name of a file that should be
deleted.
list - The first string following \"list\" will be treated as the name of a directory for which we
want a list of the files it contains.
quit - exit program
Anything else is a bad command
For a non-existent command file, you would get something like:
For a good command file like cmd.txt
cmd.txt
Your output would look something like:
Here is a template that you can use.
Once you have your program written, I want you to add the following files to the top level of
your project and run the test that I request:
cmd1.txt
cmd2.txt
Run your program with the following command line:
cmd1.txt non-existent-file cmd2.txt
Insert the contents of your screen into the appropriate JH2 worksheet.
Please don\'t create a file with the name non-existent-file!!!
Solution
Hi,
PFB the class for the question. Please comment for any queries/feedbacks.
Thanks,
Anita
FileOperations.java
package file_operations;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.text.SimpleDat.
This document provides instructions for a lab assignment to create a C++ console application to store and retrieve contact information from a sequential text file. The program will allow the user to append new records to the file by inputting names and addresses. It will also read the records from the file and display them in a formatted output. The lab consists of 5 steps: 1) requirements for the program, 2) pseudocode for processing logic, 3) creating a new project, 4) compiling and executing the program, and 5) providing screenshots and the program code in a Word document. The goal is to build upon provided code to complete the assignment of writing, reading, and displaying records to and from a sequential text file.
For the following I have finished most of this question but am havin.pdfarihantplastictanksh
For the following I have finished most of this question but am having problem with on method. I
just need the void copyNumbers method filled out. The commented out sections describe what it
needs to do. I have it started. Just need it finished.
package reading_with_exceptions;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.PrintStream;
import java.util.InputMismatchException;
import java.util.Scanner;
public class Reading_With_Exceptions {
// 1.) Create a Scanner from the inputFilename. Catch exceptions from errors.
// 2.) Read the first String from the file and use it to create a PrintStream
// catching appropriate exceptions
// 3.) Using hasNextInt and nextInt, carefully read the count integer.
// I recommend -1 for a count value if it is bad to indicate reading ALL
// 4.) Use copyNumbers method described below to complete the job
// 5.) Close Scanner and PrintStream objects
// 6.) Call printToScreen to copy the output file to the screen
void process(String inputFilename) {
int number_to_read = 0;
try {
Scanner input = new Scanner(inputFilename);
String outputFilename = input.next();
PrintStream os = new PrintStream(new FileOutputStream(outputFilename));
if ( input.hasNextInt()) {
number_to_read = input.nextInt();
}else {
number_to_read = -1;
}
copyNumbers(input, os, number_to_read);
input.close();
os.close();
printToScreen(outputFilename);
}catch (FileNotFoundException e) {
System.out.println(\"Cannot find file: \" + e);
return;
}
}
// The following routine is called to complete the job of copying integers to
// the output file:
// scan - a Scanner object to copy integers from
// ps - A PrintStream to write the integers to
// numIntsToRead - number of integers to read. A value of -1 ==> read all integers
void copyNumbers(Scanner scan, PrintStream ps, int numIntsToRead) {
// hasNext() can be used to see if the scan object still has data
// Note that hasNextInt() can be used to see if an integer is present
// nextInt() will read an integer
// next() can be used to skip over bad integers
while (scan.hasNext()) {
if (numIntsToRead < 0) {
//print out a complaint message and then read as many integers as you find.
scan.nextInt();
}
if (!scan.hasNextInt()) {
// print a complaint message and skip over the data
scan.next();
}
if ( scan < numIntsToRead) {
// complain but do not abort
}
}
}
public static void main(String[] args) {
Reading_With_Exceptions rwe = new Reading_With_Exceptions();
for (int i=0; i < args.length; i++) {
System.out.println(\"\ \ =========== Processing \"+ args[i] + \" ==========\ \");
rwe.process(args[i]);
}
}
// For the last step, we Copy the contents of the file to the screen
private void printToScreen(String filename) {
Scanner scan = null;
try {
FileInputStream fis = new FileInputStream(filename);
scan = new Scanner(fis);
while (scan.hasNextLine()) {
System.out.println(scan.nextLine());
}
}
catch (FileNotFoundException e) {
System.out.println(\"printToS.
Task #1 Correcting Logic Errors in FormulasCopy and compile the so.pdfinfo706022
Task #1 Correcting Logic Errors in Formulas
Copy and compile the source file NumericTypes.java, run the program, and observe the output.
Some of the output is incorrect. You need to correct logic errors in the average formula and the
temperature conversion formula. The logic errors could be due to conversion between data types,
order of operations, or formula problems. The necessary formulas are
average = (score1+score2) / numberOfScores
C = 5/9 (F-32)
Make sure that the output makes sense before you continue. The average of 95 and 100 should be
97.5 and the temperature that water boils is 100 degrees Celsius
Task #2 Using the Scanner Class for User Input
1. Add an import statement above the class declaration to make the Scanner
class available to your program.
2. In the main method, create a Scanner object and connect it to the System.in
object.
3. Prompt the user to enter his or her first name.
4. Read the name from the keyboard using the nextLine method, and store it into
a variable called firstName (you will need to declare any variables you use).
5. Prompt the user to enter his or her last name.
6. Read the name from the keyboard and store it in a variable called lastName.
7. Concatenate the firstName and lastName with a space between them and
store the result in a variable called fullName.
8. Print out the fullName.
9. Compile, debug, and run, using your name as test data.
10. Since we are adding on to the same program, each time we run the program we
will get the output from the previous tasks before the output of the current task.
Task #3 Working with Strings
1. Use the charAt method to get the first character in firstName and store it in a
variable called firstInitial (you will need to declare any variables that you
use).
2. Print out the user’s first initial.
3. Use the toUpperCase method to change the fullName to uppercase and store
it back into the fullName variable.
4. Add a line that prints out the value of fullName and how many characters
(including the space) are in the string stored in fullName (use the length
method to obtain that information).
5. Compile, debug, and run. The new output added on after the output from the
previous tasks should have your initials and your full name in uppercase
characters.
Task #4 Using Predefined Math Functions
Task #4 UsingPredefined Math Functions
Add a line that prompts the user to enter the diameter of a sphere.
Read in and store the number into a variable called diameter (you will need to declare any
variables that you use).
The diameter is twice as long as the radius, so calculate and store the radius in an appropriately
named variable.
The formula for the volume of a sphere is
r3
Convert the formula to Java and add a line which calculates and stores the value of volume in an
appropriately named variable. Use Math.PI for and Math.pow to cube the radius.
Print your results to the screen with an appropriate message.
Compile, debug, and run using the following test data and record the resu.
This document provides information about the Linux boot process and basic Linux commands.
1. The Linux boot process involves six main stages: BIOS, MBR, GRUB, kernel, init, and runlevel programs. BIOS loads the MBR which loads GRUB, GRUB loads the kernel and initrd, the kernel loads init, and init executes programs based on the specified runlevel.
2. Basic Linux commands demonstrated include echo, date, cal, passwd, ls, cat, wc, cp, mv, rm, head, tail, mkdir, cd, pwd, chmod, and commands using pipes, redirection, and variables.
3. The vi editor commands demonstrated are for inserting,
Article link httpiveybusinessjournal.compublicationmanaging-.docxfredharris32
Article link: http://iveybusinessjournal.com/publication/managing-global-risk-to-seize-competitive-advantage/
Requirements: Write one summary and study note both no longer than one pages should include all point of article. Then do a PPT and write a presenting paper only for 5 minutes.
Groups of students will create and offer two MS PowerPoint presentation summarizing the main points of one of the readings for this course along with a one page handout for the students in the class. The aim of the presentations and the handouts is to provide the audience with the main ideas of the article and study notes. Groups will bring to class enough copies of the handout for each student in the class. The handout should list the name of the author, the title of the article, the title of the journal, and the publication date and page numbers along with a summary of its main points. Please do not exceed one page for this material.
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.StringTokenizer;
/**
* Read a .dat file and reverse it.
*/
public class Reverse {
public static void main(String[]args) {
if (args.length != 3) {
System.err.println(" Incorrect number of arguments");
System.err.println(" Usage: ");
System.err.
println("\tjava Reverse <stack type> <input file> <output file>");
System.exit(1);
}
boolean useList = true;
if (args[0].compareTo("list")==0)
useList = true;
else if (args[0].compareTo("array")==0)
useList = false;
else {
System.err.println("\tSaw "+args[0]+" instead of list or array as first argument");
System.exit(1);
}
try {
//
// Set up the input file to read, and the output file to write to
//
BufferedReader fileIn =
new BufferedReader(new FileReader(args[1]));
PrintWriter fileOut =
new PrintWriter(new
BufferedWriter(new FileWriter(args[2])));
//
// Read the first line of the .dat file to get sample rate.
// We want to store the sample rate value in a variable,
// but we can ignore the "; Sample Rate" part of the line.
// Step through the first line one token (word) at a time
// using the StringTokenizer. The fourth token is the one
// we want (the sample rate).
//
StringTokenizer str;
String oneLine;
int sampleRate;
String strJunk;
oneLine = fileIn.readLine();
str = new StringTokenizer(oneLine);
strJunk = str.nextToken(); // Read in semicolon
strJunk = str.nextToken(); // Read in "Sample"
strJunk = str.nextToken(); // Read in "Rate"
// ...
This document discusses file handling in C++. It explains that file handling allows storing data permanently on a computer's hard disk. The key steps for file handling are naming a file, opening it, writing data, reading data, and closing the file. It also discusses various file handling functions like fstream, ifstream, ofstream and their usage for opening, reading, writing and closing files. Functions like get(), put(), tellg(), seekg() and their usage with file streams are explained. Examples are provided to demonstrate reading from and writing to files.
The document provides examples of code snippets in C# to demonstrate various OOP concepts like inheritance, polymorphism, delegates, constructors, exception handling, file I/O, and adding a flash item to a website. It also explains XML and DTDs. The code snippets show how to implement inheritance by defining a base Shape class and derived Rectangle class, implement polymorphism by overloading a print method, use delegates to call methods, define default and parameterized constructors, handle exceptions, perform file read/write operations, and add a flash file to an HTML document. The explanation of XML covers internal and external DTD declarations to define document structure.
Reaction StatisticsBackgroundWhen collecting experimental data f.pdffashionbigchennai
Reaction Statistics
Background
When collecting experimental data from chemical reactions, it’s often useful to generate
statistics based on the data. One experimental measure is the reaction rate in moles per second,
representing the amount of product formed per unit time. If we have a set of these reaction rates
collected in a data file, we can calculate summary statistical information, such as the minimum
and maximum values, the arithmetic mean, variance, and standard deviation.
Finding the minimum and maximum are straightforward: we scan through all the data, and keep
track of the smallest and largest values encountered. The arithmetic mean (or average) is defined
as:
m = (X1+X2+…+Xn)/n
where n is the number of reaction rates, and xi represents one experimental reaction rate. Once
you have the arithmetic mean, the variance can be calculated as the mean of the squares of the
deviations from the mean:
v= ((Xn-m)^2+(X2 – m^2) + …+(Xn-m)^2)/n
where n is the number of reaction rates, xi represents one experimental reaction rate, and m is the
arithmetic mean of the reaction rates. Once you have the variance, you can calculate the
standarddeviation as:
s = sqrt(v)
Assignment
You will develop a C program that reads data from an input text file containing chemical
reaction rates (in moles per second), and computes the minimum, maximum, arithmetic mean,
variance, and standard deviation for that set of data. Your instructor will provide input text files,
which will each contain a series of double values, each on a line of its own within the file. Your
program will read one of these input files into an array of doubles (i.e., it will populate the array
using the data values from the file). Your program will then calculate statistics using that array of
doubles, and will write the results out to a separate output text file.
The goals of this assignment are to provide you with experience reading and writing text data
files, provide you with experience passing an array into a function, and give you more
experience organizing your program into separate C functions.
When defining your C functions, you may either:
Define the functions before they are used by any other functions, OR
Place function prototypes near the top of your code (after all #include directives), and then define
the functions in any order.
Part 1 – Opening Files and Reading Data
Create a new Visual Studio Win32 Console project named reactionstats. Create a new C source
file named project4.c within that project. At the top of the source file, #define
_CRT_SECURE_NO_WARNINGS, and then include stdio.h, math.h, stdlib.h, stdbool.h, and
float.h.
Inside your main function, define the following:
A one-dimensional array of 600 doubles. They do not need to be initialized to anything at this
stage.
An integer variable to hold the number of elements in the array, initialized using the approach
demonstrated in class, using sizeof.
A FILE pointer variable, which will refer to the input data text file..
This presentation comes with many additional notes (pdf): http://de.slideshare.net/nicolayludwig/2-c-sharp-introductionbasicsparti-38639098
- A Tour through other .Net Programming Languages
- C# Syntax Cornerstones
1-Information sharing
2-Computation speedup
3-Modularity
4-Convenience
5-allows exchanged data and informations
Two IPC Models
1. Shared memory- is an OS provided abstraction which allows a memory region to be simultaneously accessed by multiple programs with an intent to provide communication among them. One process will create an area in RAM which other processes can accessed
2. Message passing - is a form of communication used in interprocess communication. Communication is made by the sending of messages to recipients. Each process should be able to name the other processes. The producer typically uses send() system call to send messages, and the consumer uses receive()system call to receive messages
Shared memory
Faster than message passing
After establishing shared memory, treated as routine memory accesses
Message passing
Useful for exchanging smaller amounts of data
Easy to implement, but more time-consuming task of kernel intervention
Bounded-Buffer Problem Producer Process
do {
...
produce an item in nextp
...
wait(empty);
wait(mutex);
...
add nextp to buffer
...
signal(mutex);
signal(full);
} while (true);
Bounded-Buffer Problem Consumer Process
do {
wait(full);
wait(mutex);
...
remove an item from buffer to nextc
...
signal(mutex);
signal(empty);
...
consume the item in nextc
...
} while (true);
client-server model, the client sends out requests to the server, and the server does some processing with the request(s) received, and returns a reply (or replies)to the client.
Since Socket can be described as end-points for communication. we could imagine the client and server hosts being connected by a pipe through which data-flow takes place.
1-sockets use a client-server while Server waits for incoming client requests by listening to a specified port.
2-After receiving a request, the server accepts a connection from the client socket to complete the connection
3-then Remote procedure call (RPC) abstracts procedure call mechanism for use between systems with network connections
4-and pipes acts as a conduit allowing two processes to communicate
A process is different than a program
- Program is static code and static data
- Process is Dynamic instance of code and data
-Program becomes process when executable file loaded into memory
No one-to-one mapping between programs and processes
-can have multiple processes of the same program
-one program can invoke multiple process
Execution of program started via GUI mouse clicks and command line entry of its name
The process state transition
As a process executes, The process is being created, then The process is waiting to be assigned to a processor therefore, Instructions are being executed then The process is waiting for some event to occur,thereafter The process has finished exec ...
You have been hired by Planet Poachers to write a Java console appli.pdfamitbagga0808
You have been hired by Planet Poachers to write a Java console application that reads, converts,
sorts, and writes planet data. Create text file PlanetDataEnglish.txt, paste the following data into
it, and place the file in your project folder.
PlanetDataEnglish.txt
Planet Escape Velocity (miles/s) Mean Temperature (F) Number of Moons
Mercury 2.7 333 0
Venus 6.4 867 0
Earth 7.0 59 1
Mars 3.1 -85 2
Jupiter 37.0 -166 67
Saturn 22.1 -220 62
Uranus 13.2 -320 27
Neptune 14.6 -330 13
Pluto 0.7 -375 5
Create the following methods:
Column Purpose
readTextFile To read the data from file PlanetDataEnglish.txt into four parallel arrays: planets,
escapes, means, and moons.
printArrays To print the unsorted, converted, and sorted data using the appropriate column
headers.
convertArrays To convert the escape velocities from miles/s to km/s, and to convert the mean
temperatures from Fahrenheit to Celsius.
bubbleSortArray To sort the data by planet name in ascending order. Note that when values are
swapped in one array, the same values must be swapped in the other arrays.
writeTextFile To write the data to file PlanetDataMetric.txt in the same layout as the input file.
Sample Output on .txt file
PlanetDataMetric.txt
Planet Escape Velocity (miles/s) Mean Temperature (F) Number of Moons
Earth 11.3 15 1
Jupiter 59.5 -110 67 …
Solution
Following will be program for the planet as requested
//Inclusion of the lib files
Import Java.util.scanner;
import java.io.Filewriter;
import java.io.PrintWriter;
Import java.io.FileNotFoundException;
import java.util.InputMismatchException;
import java.io.IOException;
import java.io.File;
Public class Planets // Main method is followed
{
public static void main(String[] args) // main mehtod
{
// variables are declared
scanner keyboard = new Scanner(System.in); // here the keyboard will be connected
Scanner fileIn = null; //file variable are declared
String fileInName = \"PlanetSourceData.txt\";// File name variable is declared
int i=0;
int j=0;
int k =0;
int Usednumber = 10;
String [] Plantets = new String[20];
int [] diameters = new int[15];
double [] leng = newdouble [12];
try
{
fileIn = new Scanner(new FileInputStream(fileInName)); //Scanning of the text file is done
}
Catch(FileNotFoundException e) \\\\catching of the exception
{
System.out.printIn(\"Error:File \'\" +fileInName+ \"\' not found.\"); //gives the error message that
file is not found
System.exit(-1);
}
System.out.println(\"This is templelate from Java keyboard entry\");
// To read the input file this loop is formed
while(fieIn.hasNextLine())
{
Planets[i] = fileIn.next();
diameters[j] = fileIn.nextInt();
lengths[k] = fileIn.nextDouble();
System.out.Printf(\"%-10 %8s %8s %n\" , \"Planets\", \"Diameter(miles)\",\" Hours of the
planest(Length of the planet:);
System.out.printf(\"%-10s %8d %8.1f 5n \", planets[i], diameters[j] , lenths [k]);
}
PrintArray(diameters, numberUsed);
bubbleSortArray(diameters,numberUsed); //finding the miles(escape velocity)
printArray(dua.
Here are the key points about defining a class in Python:
- A class is defined using the class keyword.
- The class name starts with a capital letter by convention.
- Attributes are defined inside the class but outside any methods. These are like variables that belong to the class.
- Methods are defined inside the class and are functions defined to perform operations on the class objects.
- The __init__() method is called automatically whenever a new object is instantiated. It is used to initialize the attributes of the object.
- To create an object of the class, the class name is used as a function. This returns a new instance of the class.
So in summary, a class groups
Penetrating Windows 8 with syringe utilityIOSR Journals
This document discusses penetrating Windows 8 remotely using Metasploit framework and syringe utility. It begins with an introduction to penetration testing and Windows 8 security. It then describes using Metasploit to generate a payload, encoding it to evade detection, and injecting it into a Windows 8 system using syringe. This allows establishing a meterpreter session and compromising the system by migrating processes and accessing the C drive. It concludes that Windows 8 has strong security but syringe injections allow compromising it, and more exploits could be found to enhance efficacy.
The document outlines the schedule and objectives for an operating systems lab course over 10 weeks. The first few weeks focus on writing programs using Unix system calls like fork, exec, wait. Later weeks involve implementing I/O system calls, simulating commands like ls and grep, and scheduling algorithms like FCFS, SJF, priority and round robin. Students are asked to display Gantt charts, compute waiting times and turnaround times for each algorithm. The final weeks cover inter-process communication, the producer-consumer problem, and memory management techniques.
The document discusses data files in Visual Basic. It provides 12 questions with explanations about key concepts related to data files, including:
1) The difference between a VB project file and data file is that a project file contains code modules while a data file stores information on the hard disk in records with fields.
2) The open statement reserves a file handle (channel) to read from and write to a file, associating a number to the handle for later access.
3) Common file modes are input, output, append, and random for different types of file access.
4) A file number maintains files in a project and is used instead of file names for reference.
Description 1) Create a Lab2 folder for this project2.docxtheodorelove43763
Description
1) Create a Lab2 folder for this project
2) Use the main driver program (called Writers.java) that I provide below to write files of differing types. You can copy and paste this code, but make sure the spaces variable copies correctly. The copy and paste operation eliminates the spaces between the quotes on some systems.
3) In the writers program, fill in the code for the three classes (Random, Binary, and Text). In each class, you will need a constructor, a write method, and a close method. The constructor opens the file, the write method writes a record, and the close method closes the file.
4) Other than what I just described, don't change the program in any way. The program asks for a file type (random, binary, or text) and the name of the file to create. In a loop it inputs a person's name (string), a person's age (int), and a person's annual salary (double). It writes to a file of the appropriate type. The loop terminates when the user indicates that inputting is complete. The program then asks if another file should be created. If the answer is yes, the whole process starts again. This and all of the java driver programs should be saved in your lab2 folder but not in the cs258 sub-folder.
5) Note: The method signatures for accessing all of the three types of files (binary, random, and text) are on the class web-site. Go to power point slides and click on week two. This will help if you didn't take accurate notes in class.
6) Write a main program to read binary files (BinReader.java). This program only needs to be able to read and display records from a Binary file that was created by the writers program.
7) Write a main program to read random files (RandReader.java). This program only needs to be able to read and display records from a Binary file that was created by the writers program. Make sure that this program reads and displays records in reverse order. DO NOT USE AN ARRAY!!!
8) In your Lab2 folder, create a subfolder within lab2 named cs258. Download Keyboard.java from the class web-site to that folder. Add a new first line of Keyboard.java with the statement, package cs258;. This line will make Keyboard.java part of the cs258 package. The driver program shown below has an import ‘cs258.*;’ statement to access the java files in this package.
9) Modify Keyboard.java. We want to extend this class so it can be extended to allow access to multiple files. The changes follow:
a. Remove all static references. This is necessary so that there will be an input stream variable (in) in each object.
b. Change the private modifier of the in and current_token variables to protected. Change the private modifier to protected in all of the signature lines of the overloaded getNextToken methods.
c. Create a constructor that instantiates the input stream for keyboard input. Remove the instantiation from the original declaration line for the in variable. The constructor doesn't need any parameters.
10)Create a class TextR.
This document provides an overview of arrays in Java, including how to declare, initialize, access, and manipulate array elements. It discusses key array concepts like indexes, the length field, and for loops for traversing arrays. Examples are provided for common array operations like initialization, accessing elements, and passing arrays as parameters or returning them from methods. Limitations of arrays are also covered.
The document discusses different types of loops in Java including while loops, do-while loops, and indefinite loops using sentinels. It provides examples of using random numbers and boolean return values from methods to implement program logic within loops. Key concepts covered include fencepost problems, random number generation, and using boolean values to represent logical tests.
This document discusses conditional execution and if/else statements in Java. It covers the basic if statement, if/else statement, relational operators, nested if/else structures, and misuse of if statements. It also discusses logical operators, evaluating logical expressions, factoring if/else code, methods that return values based on if/else conditions, and ensuring all code paths return a value. Finally, it discusses cumulative algorithms using if/else structures and loops to calculate running sums and products.
The document discusses object-oriented programming concepts like classes, objects, and methods. It provides examples of how classes act as blueprints for creating multiple objects that encapsulate both data (state) and behavior. Objects of the same class share the same methods but each object contains its own unique state data. The document uses iPods as an example - the iPod class acts as a blueprint, and individual iPod objects like iPod #1 contain their own song, volume, and battery life state details.
This document provides information about using graphics in Java, including:
- The DrawingPanel, Graphics, and Color objects used for drawing
- Common Graphics methods like drawLine, fillOval, setColor
- Coordinate system and drawing shapes at different positions
- Using loops and parameters to draw multiple shapes
- Creating simple animations using the DrawingPanel sleep method
The document discusses Java's primitive data types and for loops. It introduces Java's primitive types like int, double, char, and boolean. It covers expressions, operators, and precedence. It then introduces variables, declaring and initializing variables, and using variables in expressions. Finally, it covers the for loop structure with initialization, test, and update sections to allow repetition of code.
This document provides an introduction to Java programming. It discusses what computer science and programming are, and introduces basic Java concepts like classes, methods, and print statements. It also covers data types, variables, operators, and control structures that allow programmers to write algorithms and programs. The document uses examples like simple print programs and a cookie baking algorithm to demonstrate core Java programming concepts.
This document discusses the concept of the "myth of the lazy native" which was used during colonial times to justify European domination over Southeast Asian societies. It analyzes how this myth functioned as part of the colonial ideology and distorted the realities of indigenous societies. The introduction defines key terms like ideology and colonial capitalism used in the analysis. It notes how colonial capitalism differed from historical capitalism in Western Europe in its lack of free labor, minimal industrial development, and dualistic social structures in colonized societies.
Mobile App Development Company In Noida | Drona InfotechDrona Infotech
Drona Infotech is a premier mobile app development company in Noida, providing cutting-edge solutions for businesses.
Visit Us For : https://www.dronainfotech.com/mobile-application-development/
14 th Edition of International conference on computer visionShulagnaSarkar2
About the event
14th Edition of International conference on computer vision
Computer conferences organized by ScienceFather group. ScienceFather takes the privilege to invite speakers participants students delegates and exhibitors from across the globe to its International Conference on computer conferences to be held in the Various Beautiful cites of the world. computer conferences are a discussion of common Inventions-related issues and additionally trade information share proof thoughts and insight into advanced developments in the science inventions service system. New technology may create many materials and devices with a vast range of applications such as in Science medicine electronics biomaterials energy production and consumer products.
Nomination are Open!! Don't Miss it
Visit: computer.scifat.com
Award Nomination: https://x-i.me/ishnom
Conference Submission: https://x-i.me/anicon
For Enquiry: Computer@scifat.com
The Rising Future of CPaaS in the Middle East 2024Yara Milbes
Explore "The Rising Future of CPaaS in the Middle East in 2024" with this comprehensive PPT presentation. Discover how Communication Platforms as a Service (CPaaS) is transforming communication across various sectors in the Middle East.
A neural network is a machine learning program, or model, that makes decisions in a manner similar to the human brain, by using processes that mimic the way biological neurons work together to identify phenomena, weigh options and arrive at conclusions.
Most important New features of Oracle 23c for DBAs and Developers. You can get more idea from my youtube channel video from https://youtu.be/XvL5WtaC20A
UI5con 2024 - Bring Your Own Design SystemPeter Muessig
How do you combine the OpenUI5/SAPUI5 programming model with a design system that makes its controls available as Web Components? Since OpenUI5/SAPUI5 1.120, the framework supports the integration of any Web Components. This makes it possible, for example, to natively embed own Web Components of your design system which are created with Stencil. The integration embeds the Web Components in a way that they can be used naturally in XMLViews, like with standard UI5 controls, and can be bound with data binding. Learn how you can also make use of the Web Components base class in OpenUI5/SAPUI5 to also integrate your Web Components and get inspired by the solution to generate a custom UI5 library providing the Web Components control wrappers for the native ones.
A Comprehensive Guide on Implementing Real-World Mobile Testing Strategies fo...kalichargn70th171
In today's fiercely competitive mobile app market, the role of the QA team is pivotal for continuous improvement and sustained success. Effective testing strategies are essential to navigate the challenges confidently and precisely. Ensuring the perfection of mobile apps before they reach end-users requires thoughtful decisions in the testing plan.
Consistent toolbox talks are critical for maintaining workplace safety, as they provide regular opportunities to address specific hazards and reinforce safe practices.
These brief, focused sessions ensure that safety is a continual conversation rather than a one-time event, which helps keep safety protocols fresh in employees' minds. Studies have shown that shorter, more frequent training sessions are more effective for retention and behavior change compared to longer, infrequent sessions.
Engaging workers regularly, toolbox talks promote a culture of safety, empower employees to voice concerns, and ultimately reduce the likelihood of accidents and injuries on site.
The traditional method of conducting safety talks with paper documents and lengthy meetings is not only time-consuming but also less effective. Manual tracking of attendance and compliance is prone to errors and inconsistencies, leading to gaps in safety communication and potential non-compliance with OSHA regulations. Switching to a digital solution like Safelyio offers significant advantages.
Safelyio automates the delivery and documentation of safety talks, ensuring consistency and accessibility. The microlearning approach breaks down complex safety protocols into manageable, bite-sized pieces, making it easier for employees to absorb and retain information.
This method minimizes disruptions to work schedules, eliminates the hassle of paperwork, and ensures that all safety communications are tracked and recorded accurately. Ultimately, using a digital platform like Safelyio enhances engagement, compliance, and overall safety performance on site. https://safelyio.com/
What to do when you have a perfect model for your software but you are constrained by an imperfect business model?
This talk explores the challenges of bringing modelling rigour to the business and strategy levels, and talking to your non-technical counterparts in the process.
8 Best Automated Android App Testing Tool and Framework in 2024.pdfkalichargn70th171
Regarding mobile operating systems, two major players dominate our thoughts: Android and iPhone. With Android leading the market, software development companies are focused on delivering apps compatible with this OS. Ensuring an app's functionality across various Android devices, OS versions, and hardware specifications is critical, making Android app testing essential.
Top Benefits of Using Salesforce Healthcare CRM for Patient Management.pdfVALiNTRY360
Salesforce Healthcare CRM, implemented by VALiNTRY360, revolutionizes patient management by enhancing patient engagement, streamlining administrative processes, and improving care coordination. Its advanced analytics, robust security, and seamless integration with telehealth services ensure that healthcare providers can deliver personalized, efficient, and secure patient care. By automating routine tasks and providing actionable insights, Salesforce Healthcare CRM enables healthcare providers to focus on delivering high-quality care, leading to better patient outcomes and higher satisfaction. VALiNTRY360's expertise ensures a tailored solution that meets the unique needs of any healthcare practice, from small clinics to large hospital systems.
For more info visit us https://valintry360.com/solutions/health-life-sciences
E-commerce Development Services- Hornet DynamicsHornet Dynamics
For any business hoping to succeed in the digital age, having a strong online presence is crucial. We offer Ecommerce Development Services that are customized according to your business requirements and client preferences, enabling you to create a dynamic, safe, and user-friendly online store.
How Can Hiring A Mobile App Development Company Help Your Business Grow?ToXSL Technologies
ToXSL Technologies is an award-winning Mobile App Development Company in Dubai that helps businesses reshape their digital possibilities with custom app services. As a top app development company in Dubai, we offer highly engaging iOS & Android app solutions. https://rb.gy/necdnt
Everything You Need to Know About X-Sign: The eSign Functionality of XfilesPr...XfilesPro
Wondering how X-Sign gained popularity in a quick time span? This eSign functionality of XfilesPro DocuPrime has many advancements to offer for Salesforce users. Explore them now!
2. 2
Input/output (I/O)
import java.io.*;
• Create a File object to get info about a file on your drive.
– (This doesn't actually create a new file on the hard disk.)
File f = new File("example.txt");
if (f.exists() && f.length() > 1000) {
f.delete();
}
Method name Description
canRead() returns whether file is able to be read
delete() removes file from disk
exists() whether this file exists on disk
getName() returns file's name
length() returns number of bytes in file
renameTo(file) changes name of file
3. 3
Reading files
• To read a file, pass a File when constructing a Scanner.
Scanner name = new Scanner(new File("file name"));
– Example:
File file = new File("mydata.txt");
Scanner input = new Scanner(file);
– or (shorter):
Scanner input = new Scanner(new File("mydata.txt"));
4. 4
File paths
• absolute path: specifies a drive or a top "/" folder
C:/Documents/smith/hw6/input/data.csv
– Windows can also use backslashes to separate folders.
• relative path: does not specify any top-level folder
names.dat
input/kinglear.txt
– Assumed to be relative to the current directory:
Scanner input = new Scanner(new
File("data/readme.txt"));
If our program is in H:/hw6 ,
Scanner will look for H:/hw6/data/readme.txt
5. 5
Compiler error w/ files
import java.io.*; // for File
import java.util.*; // for Scanner
public class ReadFile {
public static void main(String[] args) {
Scanner input = new Scanner(new File("data.txt"));
String text = input.next();
System.out.println(text);
}
}
• The program fails to compile with the following error:
ReadFile.java:6: unreported exception
java.io.FileNotFoundException;
must be caught or declared to be thrown
Scanner input = new Scanner(new File("data.txt"));
^
6. 6
Exceptions
• exception: An object representing a runtime error.
• dividing an integer by 0
• calling substring on a String and passing too large an index
• trying to read the wrong type of value from a Scanner
• trying to read a file that does not exist
– We say that a program with an error "throws" an exception.
– It is also possible to "catch" (handle or fix) an exception.
• checked exception: An error that must be handled by our
program (otherwise it will not compile).
– We must specify how our program will handle file I/O failures.
7. 7
The throws clause
• throws clause: Keywords on a method's header that state
that it may generate an exception (and will not handle it).
• Syntax:
public static type name(params) throws type {
– Example:
public class ReadFile {
public static void main(String[] args)
throws FileNotFoundException {
– Like saying, "I hereby announce that this method might throw an
exception, and I accept the consequences if this happens."
8. 8
Input tokens
• token: A unit of user input, separated by whitespace.
– A Scanner splits a file's contents into tokens.
• If an input file contains the following:
23 3.14
"John Smith"
The Scanner can interpret the tokens as the following types:
Token Type(s)
23 int, double, String
3.14 double, String
"John String
Smith" String
9. 9
Files and input cursor
• Consider a file weather.txt that contains this text:
16.2 23.5
19.1 7.4 22.8
18.5 -1.8 14.9
• A Scanner views all input as a stream of characters:
16.2 23.5n19.1 7.4 22.8nn18.5 -1.8 14.9n
^
• input cursor: The current position of the Scanner.
10. 10
Consuming tokens
• consuming input: Reading input and advancing the cursor.
– Calling nextInt etc. moves the cursor past the current token.
16.2 23.5n19.1 7.4 22.8nn18.5 -1.8 14.9n
^
double d = input.nextDouble(); // 16.2
16.2 23.5n19.1 7.4 22.8nn18.5 -1.8 14.9n
^
String s = input.next(); // "23.5"
16.2 23.5n19.1 7.4 22.8nn18.5 -1.8 14.9n
^
11. 11
File input question
• Recall the input file weather.txt:
16.2 23.5
19.1 7.4 22.8
18.5 -1.8 14.9
• Write a program that prints the change in temperature
between each pair of neighboring days.
16.2 to 23.5, change = 7.3
23.5 to 19.1, change = -4.4
19.1 to 7.4, change = -11.7
7.4 to 22.8, change = 15.4
22.8 to 18.5, change = -4.3
18.5 to -1.8, change = -20.3
-1.8 to 14.9, change = 16.7
12. 12
File input answer
// Displays changes in temperature from data in an input file.
import java.io.*; // for File
import java.util.*; // for Scanner
public class Temperatures {
public static void main(String[] args)
throws FileNotFoundException {
Scanner input = new Scanner(new File("weather.txt"));
double prev = input.nextDouble(); // fencepost
for (int i = 1; i <= 7; i++) {
double next = input.nextDouble();
System.out.println(prev + " to " + next +
", change = " + (next - prev));
prev = next;
}
}
}
13. 13
Reading an entire file
• Suppose we want our program to work no matter how many
numbers are in the file.
– Currently, if the file has more numbers, they will not be read.
– If the file has fewer numbers, what will happen?
A crash! Example output from a file with just 3 numbers:
16.2 to 23.5, change = 7.3
23.5 to 19.1, change = -4.4
Exception in thread "main"
java.util.NoSuchElementException
at java.util.Scanner.throwFor(Scanner.java:838)
at java.util.Scanner.next(Scanner.java:1347)
at Temperatures.main(Temperatures.java:12)
14. 14
Scanner exceptions
• NoSuchElementException
– You read past the end of the input.
• InputMismatchException
– You read the wrong type of token (e.g. read "hi" as an int).
• Finding and fixing these exceptions:
– Read the exception text for line numbers in your code
(the first line that mentions your file; often near the bottom):
Exception in thread "main"
java.util.NoSuchElementException
at java.util.Scanner.throwFor(Scanner.java:838)
at java.util.Scanner.next(Scanner.java:1347)
at MyProgram.myMethodName(MyProgram.java:19)
at MyProgram.main(MyProgram.java:6)
15. 15
Scanner tests for valid input
• These methods of the Scanner do not consume input;
they just give information about what the next token will be.
– Useful to see what input is coming, and to avoid crashes.
– These methods can be used with a console Scanner, as well.
• When called on the console, they sometimes pause waiting for input.
Method Description
hasNext() returns true if there is a next token
hasNextInt() returns true if there is a next token
and it can be read as an int
hasNextDouble() returns true if there is a next token
and it can be read as a double
16. 16
Using hasNext methods
• Avoiding type mismatches:
Scanner console = new Scanner(System.in);
System.out.print("How old are you? ");
if (console.hasNextInt()) {
int age = console.nextInt(); // will not crash!
System.out.println("Wow, " + age + " is old!");
} else {
System.out.println("You didn't type an integer.");
}
• Avoiding reading past the end of a file:
Scanner input = new Scanner(new File("example.txt"));
if (input.hasNext()) {
String token = input.next(); // will not crash!
System.out.println("next token is " + token);
}
17. 17
File input question 2
• Modify the temperature program to process the entire file,
regardless of how many numbers it contains.
– Example: If a ninth day's data is added, output might be:
16.2 to 23.5, change = 7.3
23.5 to 19.1, change = -4.4
19.1 to 7.4, change = -11.7
7.4 to 22.8, change = 15.4
22.8 to 18.5, change = -4.3
18.5 to -1.8, change = -20.3
-1.8 to 14.9, change = 16.7
14.9 to 16.1, change = 1.2
18. 18
File input answer 2
// Displays changes in temperature from data in an input file.
import java.io.*; // for File
import java.util.*; // for Scanner
public class Temperatures {
public static void main(String[] args)
throws FileNotFoundException {
Scanner input = new Scanner(new File("weather.txt"));
double prev = input.nextDouble(); // fencepost
while (input.hasNextDouble()) {
double next = input.nextDouble();
System.out.println(prev + " to " + next +
", change = " + (next - prev));
prev = next;
}
}
}
19. 19
File input question 3
• Modify the temperature program to handle files that contain
non-numeric tokens (by skipping them).
• For example, it should produce the same output as before
when given this input file, weather2.txt:
16.2 23.5
Tuesday 19.1 Wed 7.4 THURS. TEMP: 22.8
18.5 -1.8 <-- Marty here is my data! --Kim
14.9 :-)
– You may assume that the file begins with a real number.
20. 20
File input answer 3
// Displays changes in temperature from data in an input file.
import java.io.*; // for File
import java.util.*; // for Scanner
public class Temperatures2 {
public static void main(String[] args)
throws FileNotFoundException {
Scanner input = new Scanner(new File("weather.txt"));
double prev = input.nextDouble(); // fencepost
while (input.hasNext()) {
if (input.hasNextDouble()) {
double next = input.nextDouble();
System.out.println(prev + " to " + next +
", change = " + (next - prev));
prev = next;
} else {
input.next(); // throw away unwanted token
}
}
}
}
21. 21
Election question
• Write a program that reads a file poll.txt of poll data.
– Format: State Obama% McCain% ElectoralVotes Pollster
CT 56 31 7 Oct U. of Connecticut
NE 37 56 5 Sep Rasmussen
AZ 41 49 10 Oct Northern Arizona U.
• The program should print how many electoral votes each
candidate leads in, and who is leading overall in the polls.
Obama : 214 votes
McCain: 257 votes
22. 22
Election answer
// Computes leader in presidential polls, based on input file such as:
// AK 42 53 3 Oct Ivan Moore Research
import java.io.*; // for File
import java.util.*; // for Scanner
public class Election {
public static void main(String[] args) throws FileNotFoundException {
Scanner input = new Scanner(new File("polls.txt"));
int obamaVotes = 0, mccainVotes = 0;
while (input.hasNext()) {
if (input.hasNextInt()) {
int obama = input.nextInt();
int mccain = input.nextInt();
int eVotes = input.nextInt();
if (obama > mccain) {
obamaVotes = obamaVotes + eVotes;
} else if (mccain > obama) {
mccainVotes = mccainVotes + eVotes;
}
} else {
input.next(); // skip non-integer token
}
}
System.out.println("Obama : " + obamaVotes + " votes");
System.out.println("McCain: " + mccainVotes + " votes");
}
}
23. 23
Hours question
• Given a file hours.txt with the following contents:
123 Kim 12.5 8.1 7.6 3.2
456 Eric 4.0 11.6 6.5 2.7 12
789 Stef 8.0 8.0 8.0 8.0 7.5
– Consider the task of computing hours worked by each person:
Kim (ID#123) worked 31.4 hours (7.85 hours/day)
Eric (ID#456) worked 36.8 hours (7.36 hours/day)
Stef (ID#789) worked 39.5 hours (7.9 hours/day)
• Let's try to solve this problem token-by-token ...
24. 24
Hours answer (flawed)
// This solution does not work!
import java.io.*; // for File
import java.util.*; // for Scanner
public class HoursWorked {
public static void main(String[] args)
throws FileNotFoundException {
Scanner input = new Scanner(new File("hours.txt"));
while (input.hasNext()) {
// process one person
int id = input.nextInt();
String name = input.next();
double totalHours = 0.0;
int days = 0;
while (input.hasNextDouble()) {
totalHours += input.nextDouble();
days++;
}
System.out.println(name + " (ID#" + id +
") worked " + totalHours + " hours (" +
(totalHours / days) + " hours/day)");
}
}
}
25. 25
Flawed output
Susan (ID#123) worked 487.4 hours (97.48 hours/day)
Exception in thread "main"
java.util.InputMismatchException
at java.util.Scanner.throwFor(Scanner.java:840)
at java.util.Scanner.next(Scanner.java:1461)
at java.util.Scanner.nextInt(Scanner.java:2091)
at HoursWorked.main(HoursBad.java:9)
– The inner while loop is grabbing the next person's ID.
– We want to process the tokens, but we also care about the line
breaks (they mark the end of a person's data).
• A better solution is a hybrid approach:
– First, break the overall input into lines.
– Then break each line into tokens.
26. 26
Line-based Scanners
Scanner input = new Scanner(new File("file name"));
while (input.hasNextLine()) {
String line = input.nextLine();
process this line;
}
Method Description
nextLine() returns next entire line of input (from cursor to n)
hasNextLine() returns true if there are any more lines of input to
read (always true for console input)
27. 27
Consuming lines of input
23 3.14 John Smith "Hello" world
45.2 19
• The Scanner reads the lines as follows:
23t3.14 John Smitht"Hello" worldntt45.2 19n
^
– String line = input.nextLine();
23t3.14 John Smitht"Hello" worldntt45.2 19n
^
– String line2 = input.nextLine();
23t3.14 John Smitht"Hello" worldntt45.2 19n
^
– Each n character is consumed but not returned.
28. 28
Scanners on Strings
• A Scanner can tokenize the contents of a String:
Scanner name = new Scanner(String);
– Example:
String text = "15 3.2 hello 9 27.5";
Scanner scan = new Scanner(text);
int num = scan.nextInt();
System.out.println(num); // 15
double num2 = scan.nextDouble();
System.out.println(num2); // 3.2
String word = scan.next();
System.out.println(word); // hello
29. 29
Mixing lines and tokens
// Counts the words on each line of a file
Scanner input = new Scanner(new File("input.txt"));
while (input.hasNextLine()) {
String line = input.nextLine();
Scanner lineScan = new Scanner(line);
// process the contents of this line
int count = 0;
while (lineScan.hasNext()) {
String word = lineScan.next();
count++;
}
System.out.println("Line has " + count + " words");
}
Input file input.txt: Output to console:
The quick brown fox jumps over
the lazy dog.
Line has 6 words
Line has 3 words
30. 30
Hours question
• Fix the Hours program to read the input file properly:
123 Kim 12.5 8.1 7.6 3.2
456 Eric 4.0 11.6 6.5 2.7 12
789 Stef 8.0 8.0 8.0 8.0 7.5
– Recall, it should produce the following output:
Kim (ID#123) worked 31.4 hours (7.85 hours/day)
Eric (ID#456) worked 36.8 hours (7.36 hours/day)
Stef (ID#789) worked 39.5 hours (7.9 hours/day)
31. 31
Hours answer, corrected
// Processes an employee input file and outputs each employee's hours.
import java.io.*; // for File
import java.util.*; // for Scanner
public class Hours {
public static void main(String[] args) throws FileNotFoundException {
Scanner input = new Scanner(new File("hours.txt"));
while (input.hasNextLine()) {
String line = input.nextLine();
Scanner lineScan = new Scanner(line);
int id = lineScan.nextInt(); // e.g. 456
String name = lineScan.next(); // e.g. "Eric"
double sum = 0.0;
int count = 0;
while (lineScan.hasNextDouble()) {
sum = sum + lineScan.nextDouble();
count++;
}
double average = sum / count;
System.out.println(name + " (ID#" + id + ") worked " +
sum + " hours (" + average + " hours/day)");
}
}
}
33. 33
Output to files
• PrintStream: An object in the java.io package that lets
you print output to a destination such as a file.
– Any methods you have used on System.out
(such as print, println) will work on a PrintStream.
• Syntax:
PrintStream name = new PrintStream(new File("file name"));
Example:
PrintStream output = new PrintStream(new File("out.txt"));
output.println("Hello, file!");
output.println("This is a second line of output.");
34. 34
Details about PrintStream
PrintStream name = new PrintStream(new File("file name"));
– If the given file does not exist, it is created.
– If the given file already exists, it is overwritten.
– The output you print appears in a file, not on the console.
You will have to open the file with an editor to see it.
– Do not open the same file for both reading (Scanner)
and writing (PrintStream) at the same time.
• You will overwrite your input file with an empty file (0 bytes).
35. 35
System.out and PrintStream
• The console output object, System.out, is a PrintStream.
PrintStream out1 = System.out;
PrintStream out2 = new PrintStream(new File("data.txt"));
out1.println("Hello, console!"); // goes to console
out2.println("Hello, file!"); // goes to file
– A reference to it can be stored in a PrintStream variable.
• Printing to that variable causes console output to appear.
– You can pass System.out to a method as a PrintStream.
• Allows a method to send output to the console or a file.
36. 36
PrintStream question
• Modify our previous Hours program to use a PrintStream to
send its output to the file hours_out.txt.
– The program will produce no console output.
– But the file hours_out.txt will be created with the text:
Kim (ID#123) worked 31.4 hours (7.85 hours/day)
Eric (ID#456) worked 36.8 hours (7.36 hours/day)
Stef (ID#789) worked 39.5 hours (7.9 hours/day)
37. 37
PrintStream answer
// Processes an employee input file and outputs each employee's hours.
import java.io.*; // for File
import java.util.*; // for Scanner
public class Hours2 {
public static void main(String[] args) throws FileNotFoundException {
Scanner input = new Scanner(new File("hours.txt"));
PrintStream out = new PrintStream(new File("hours_out.txt"));
while (input.hasNextLine()) {
String line = input.nextLine();
Scanner lineScan = new Scanner(line);
int id = lineScan.nextInt(); // e.g. 456
String name = lineScan.next(); // e.g. "Eric"
double sum = 0.0;
int count = 0;
while (lineScan.hasNextDouble()) {
sum = sum + lineScan.nextDouble();
count++;
}
double average = sum / count;
out.println(name + " (ID#" + id + ") worked " +
sum + " hours (" + average + " hours/day)");
}
}
}
38. 38
Prompting for a file name
• We can ask the user to tell us the file to read.
– The filename might have spaces; use nextLine(), not next()
// prompt for input file name
Scanner console = new Scanner(System.in);
System.out.print("Type a file name to use: ");
String filename = console.nextLine();
Scanner input = new Scanner(new File(filename));
• Files have an exists method to test for file-not-found:
File file = new File("hours.txt");
if (!file.exists()) {
// try a second input file as a backup
System.out.print("hours file not found!");
file = new File("hours2.txt");
}
39. 39
Mixing tokens and lines
• Using nextLine in conjunction with the token-based methods
on the same Scanner can cause bad results.
23 3.14
Joe "Hello" world
45.2 19
– You'd think you could read 23 and 3.14 with nextInt and
nextDouble, then read Joe "Hello" world with nextLine .
System.out.println(input.nextInt()); // 23
System.out.println(input.nextDouble()); // 3.14
System.out.println(input.nextLine()); //
– But the nextLine call produces no output! Why?
40. 40
Mixing lines and tokens
• Don't read both tokens and lines from the same Scanner:
23 3.14
Joe "Hello world"
45.2 19
input.nextInt() // 23
23t3.14nJoet"Hello" worldntt45.2 19n
^
input.nextDouble() // 3.14
23t3.14nJoet"Hello" worldntt45.2 19n
^
input.nextLine() // "" (empty!)
23t3.14nJoet"Hello" worldntt45.2 19n
^
input.nextLine() // "Joet"Hello" world"
23t3.14nJoet"Hello" worldntt45.2 19n
^
41. 41
Line-and-token example
Scanner console = new Scanner(System.in);
System.out.print("Enter your age: ");
int age = console.nextInt();
System.out.print("Now enter your name: ");
String name = console.nextLine();
System.out.println(name + " is " + age + " years old.");
Log of execution (user input underlined):
Enter your age: 12
Now enter your name: Sideshow Bob
is 12 years old.
• Why?
– Overall input: 12nSideshow Bob
– After nextInt(): 12nSideshow Bob
^
– After nextLine(): 12nSideshow Bob
^