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.
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.
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..
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.
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..
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.
Core Java Programming Language (JSE) : Chapter XI - Console I/O and File I/OWebStackAcademy
Java.io.File Class in Java. The File class is Java's representation of a file or directory path name. ... A file system may implement restrictions to certain operations on the actual file-system object, such as reading, writing, and executing. These restrictions are collectively known as access permissions.
The program uses console I/O to simply read its "standard input (stdin)"—which might be the keyboard, a file dump, or the output of some other program—and print to its "standard output (stdout)"—which might be the display or printer or another program or a file.
Change the code in Writer.java only to get it working. Must contain .pdfsecunderbadtirumalgi
Change the code in Writer.java only to get it working. Must contain methods: logReverse() ,
logMax(), logDuplicates(),
This lab is going to focus on File Output, which you will find is somewhat similar to console
output.
FileMain.java
import java.io.IOException;
import java.util.ArrayList;
import java.util.Scanner;
public class FileMain {
public static void main(String[] args) throws IOException{
Scanner scnr = new Scanner(System.in);
System.out.print("Please enter the name of the file you would like to read: ");
String fileName = scnr.next();
Reader reader = new Reader();
ArrayList fileContents = reader.getFileContents(fileName);
System.out.println("Please enter a name for your new file: ");
String newFileName = scnr.next();
Writer fileOut = new Writer(newFileName);
fileOut.logReverse(fileContents);
fileOut.logMax(fileContents);
fileOut.logDuplicates(fileContents);
fileOut.closeWriter();
scnr.close();
}
}
Filetester.java
import java.io.IOException;
import java.util.ArrayList;
public class FileTester {
public static boolean testLogReverse(ArrayList contents) throws IOException {
Writer writer = new Writer("logReverseTest.txt");
writer.logReverse(contents);
writer.closeWriter();
ArrayList expected = new ArrayList();
expected.add("Reversed file contents: ");
expected.add("58");
expected.add("12");
expected.add("19");
expected.add("42");
expected.add("12");
expected.add("End of file.");
Reader testReader = new Reader();
ArrayList result = testReader.getFileContents("logReverseTest.txt");
if(expected.equals(result)) return true;
else return false;
}
public static boolean testLogMax(ArrayList contents) throws IOException {
Writer writer = new Writer("logMaxTest.txt");
writer.logMax(contents);
writer.closeWriter();
ArrayList expected = new ArrayList();
expected.add("The largest number in the file is: 58");
expected.add("End of file.");
Reader testReader = new Reader();
ArrayList result = testReader.getFileContents("logMaxTest.txt");
if(expected.equals(result)) return true;
else return false;
}
public static boolean testLogDuplicates(ArrayList contents) throws IOException {
Writer writer = new Writer("logDuplicatesTest.txt");
writer.logDuplicates(contents);
writer.closeWriter();
ArrayList expected = new ArrayList();
expected.add("Duplicates found: true");
expected.add("End of file.");
Reader testReader = new Reader();
ArrayList result = testReader.getFileContents("logDuplicatesTest.txt");
if(expected.equals(result)) return true;
else return false;
}
public static void main(String[] args) throws IOException {
Reader reader = new Reader();
ArrayList fileContents = reader.getFileContents("nums.txt");
System.out.println("logReverse test passed? " + testLogReverse(fileContents));
System.out.println("logMax test passed? " + testLogMax(fileContents));
System.out.println("logDuplicates test passed? " + testLogDuplicates(fileContents));
}
}
Reader.java
import java.io.File;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.Sca.
Write a program that will count the number of characters- words- and l.docxlez31palka
Write a program that will count the number of characters, words, and lines in a file. Words are separated by whitespace characters. The file name should be passed as a command-line argument, as shown;
c:\\exercise>java Exercise12_13 Loan.java
File Loan.java has
1919 characters
210 words
71 lines
c:\\exercise>
Solution
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
import java.util.StringTokenizer;
public class ass1
{
public static void main(String[] args) throws FileNotFoundException
{
//Â Â Scanner console = new Scanner(System.in);
System.out.println(args[0]);
//System.out.println(args[1]);
//System.out.println(args[2]);
String inputFile=args[0];
File file = new File(inputFile);
Scanner in = new Scanner(file);
int words = 0;
int lines = 0;
int chars = 0;
while(in.hasNextLine()) {
lines++;
String line = in.nextLine();
chars += line.length();
words += new StringTokenizer(line, \" \").countTokens();
}
System.out.println(\"characters are \"+chars);
System.out.println(\"words are \"+words);
System.out.println(\"lines are \"+lines);
}
}
.
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.
Write a program in java that asks a user for a file name and prints .pdfatulkapoor33
Write a program in java that asks a user for a file name and prints the number of characters,
words (separated by whitespace), and lines in that file. Then, it replaces each line of the file with
its reverse. For example, if the file contains the following lines (Test1.txt):
This is a test
Hi there
Output on the console:
Number of characters: 22
Number of words: 6
Number of lines: 2
Data written to the file (Test1.txt):
tset a si sihT
ereth iH
Solution
ReadFileCount.java
import java.io.File;
import java.io.FileNotFoundException;
import java.io.PrintStream;
import java.util.Scanner;
public class ReadFileCount {
public static void main(String[] args) throws FileNotFoundException {
Scanner scan = new Scanner(System.in);
System.out.println(\"Enter file name: \");
String fileName = scan.next();
StringBuffer finalsb = new StringBuffer();
File file = new File(fileName);
if(file.exists()){
int numberOfLines = 0;
int numberOfCharacters = 0;
int numberOfWords = 0;
Scanner scan1 = new Scanner(file);;
while(scan1.hasNextLine()){
StringBuffer sb = new StringBuffer();
String s = scan1.nextLine();
sb.append(s);
numberOfLines++;
numberOfCharacters = numberOfCharacters + s.length();
String words[] = s.split(\" \");
numberOfWords = numberOfWords + words.length;
finalsb.append(sb.reverse());
finalsb.append(\"\ \");
}
System.out.println(\"Number of characters: \"+numberOfCharacters);
System.out.println(\"Number of words: \"+numberOfWords);
System.out.println(\"Number of lines : \"+numberOfLines);
PrintStream ps =new PrintStream(file);
ps.print(finalsb.toString());
ps.flush();
ps.close();
System.out.println(\"Data written to the file \"+fileName);
}
else{
System.out.println(\"File does not exist\");
}
}
}
Output:
Enter file name:
D:\\\\Test1.txt
Number of characters: 0
Number of words: 0
Number of lines : 0
Data written to the file D:\\\\Test1.txt
Test1.txt
tset a si sihT
ereht iH.
Use Java to program the following.1. Create public java class name.pdff3apparelsonline
Use Java to program the following.
1. Create public java class named Benford.
2. It\'s main function should prompt for the name of a data file and then the function iterates
through the all of the elements in the data file and computes the frequency (count and
percentage) of the first number in each entry.
3. Note: Some of the data files have comments that you must filter out.
4. Also note: that blank lines or lines where the number begins or is 0 must also be filtered out.
5. Your output must be formatted as follows.
Solution
Hi Firend, Please find my code.
Please let me know in case of any issue.
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class CountFrequency {
public static void main(String[] args) throws FileNotFoundException {
Scanner sc = new Scanner(System.in);
// taking input file name
System.out.print(\"Enter input file name: \");
String fileName = sc.next();
// opening input file
Scanner inputFile = new Scanner(new File(fileName));
// declaring array to store count of first digit of each entery
int[] frequency = new int[10];
int totalCount = 0; // to maintain total count
int num;
// reading all lines
while(inputFile.hasNextLine()){
// reading current line
String line = inputFile.nextLine();
// if line is not empty
if(line == null || line.isEmpty() || line.trim() == \"\")
continue;
// taking first character of current line
char firstDigit = line.charAt(0);
// if first character is digit and not equal to 0
if(Character.isDigit(firstDigit) && firstDigit != \'0\'){
// converting first character of current line in integer
int d = firstDigit - \'0\';
frequency[d]++;
totalCount++;
}
}
System.out.println(\"Digit\\tCount\\tFrequency\");
for(int i=1; i<=9; i++){
System.out.println(i+\"\\t\"+frequency[i]+\"\\t\"+
((double)frequency[i]/(double)totalCount*100));
}
}
}
/*
Sample run:
##### Entry of input.txt:
453 43
//543
123
0
4ee
875
52
// Output
Enter input file name: input.txt
Digit Count Frequency
1 1 20.0
2 0 0.0
3 0 0.0
4 2 40.0
5 1 20.0
6 0 0.0
7 0 0.0
8 1 20.0
9 0 0.0
*/.
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.
Core Java Programming Language (JSE) : Chapter XI - Console I/O and File I/OWebStackAcademy
Java.io.File Class in Java. The File class is Java's representation of a file or directory path name. ... A file system may implement restrictions to certain operations on the actual file-system object, such as reading, writing, and executing. These restrictions are collectively known as access permissions.
The program uses console I/O to simply read its "standard input (stdin)"—which might be the keyboard, a file dump, or the output of some other program—and print to its "standard output (stdout)"—which might be the display or printer or another program or a file.
Change the code in Writer.java only to get it working. Must contain .pdfsecunderbadtirumalgi
Change the code in Writer.java only to get it working. Must contain methods: logReverse() ,
logMax(), logDuplicates(),
This lab is going to focus on File Output, which you will find is somewhat similar to console
output.
FileMain.java
import java.io.IOException;
import java.util.ArrayList;
import java.util.Scanner;
public class FileMain {
public static void main(String[] args) throws IOException{
Scanner scnr = new Scanner(System.in);
System.out.print("Please enter the name of the file you would like to read: ");
String fileName = scnr.next();
Reader reader = new Reader();
ArrayList fileContents = reader.getFileContents(fileName);
System.out.println("Please enter a name for your new file: ");
String newFileName = scnr.next();
Writer fileOut = new Writer(newFileName);
fileOut.logReverse(fileContents);
fileOut.logMax(fileContents);
fileOut.logDuplicates(fileContents);
fileOut.closeWriter();
scnr.close();
}
}
Filetester.java
import java.io.IOException;
import java.util.ArrayList;
public class FileTester {
public static boolean testLogReverse(ArrayList contents) throws IOException {
Writer writer = new Writer("logReverseTest.txt");
writer.logReverse(contents);
writer.closeWriter();
ArrayList expected = new ArrayList();
expected.add("Reversed file contents: ");
expected.add("58");
expected.add("12");
expected.add("19");
expected.add("42");
expected.add("12");
expected.add("End of file.");
Reader testReader = new Reader();
ArrayList result = testReader.getFileContents("logReverseTest.txt");
if(expected.equals(result)) return true;
else return false;
}
public static boolean testLogMax(ArrayList contents) throws IOException {
Writer writer = new Writer("logMaxTest.txt");
writer.logMax(contents);
writer.closeWriter();
ArrayList expected = new ArrayList();
expected.add("The largest number in the file is: 58");
expected.add("End of file.");
Reader testReader = new Reader();
ArrayList result = testReader.getFileContents("logMaxTest.txt");
if(expected.equals(result)) return true;
else return false;
}
public static boolean testLogDuplicates(ArrayList contents) throws IOException {
Writer writer = new Writer("logDuplicatesTest.txt");
writer.logDuplicates(contents);
writer.closeWriter();
ArrayList expected = new ArrayList();
expected.add("Duplicates found: true");
expected.add("End of file.");
Reader testReader = new Reader();
ArrayList result = testReader.getFileContents("logDuplicatesTest.txt");
if(expected.equals(result)) return true;
else return false;
}
public static void main(String[] args) throws IOException {
Reader reader = new Reader();
ArrayList fileContents = reader.getFileContents("nums.txt");
System.out.println("logReverse test passed? " + testLogReverse(fileContents));
System.out.println("logMax test passed? " + testLogMax(fileContents));
System.out.println("logDuplicates test passed? " + testLogDuplicates(fileContents));
}
}
Reader.java
import java.io.File;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.Sca.
Write a program that will count the number of characters- words- and l.docxlez31palka
Write a program that will count the number of characters, words, and lines in a file. Words are separated by whitespace characters. The file name should be passed as a command-line argument, as shown;
c:\\exercise>java Exercise12_13 Loan.java
File Loan.java has
1919 characters
210 words
71 lines
c:\\exercise>
Solution
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
import java.util.StringTokenizer;
public class ass1
{
public static void main(String[] args) throws FileNotFoundException
{
//Â Â Scanner console = new Scanner(System.in);
System.out.println(args[0]);
//System.out.println(args[1]);
//System.out.println(args[2]);
String inputFile=args[0];
File file = new File(inputFile);
Scanner in = new Scanner(file);
int words = 0;
int lines = 0;
int chars = 0;
while(in.hasNextLine()) {
lines++;
String line = in.nextLine();
chars += line.length();
words += new StringTokenizer(line, \" \").countTokens();
}
System.out.println(\"characters are \"+chars);
System.out.println(\"words are \"+words);
System.out.println(\"lines are \"+lines);
}
}
.
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.
Write a program in java that asks a user for a file name and prints .pdfatulkapoor33
Write a program in java that asks a user for a file name and prints the number of characters,
words (separated by whitespace), and lines in that file. Then, it replaces each line of the file with
its reverse. For example, if the file contains the following lines (Test1.txt):
This is a test
Hi there
Output on the console:
Number of characters: 22
Number of words: 6
Number of lines: 2
Data written to the file (Test1.txt):
tset a si sihT
ereth iH
Solution
ReadFileCount.java
import java.io.File;
import java.io.FileNotFoundException;
import java.io.PrintStream;
import java.util.Scanner;
public class ReadFileCount {
public static void main(String[] args) throws FileNotFoundException {
Scanner scan = new Scanner(System.in);
System.out.println(\"Enter file name: \");
String fileName = scan.next();
StringBuffer finalsb = new StringBuffer();
File file = new File(fileName);
if(file.exists()){
int numberOfLines = 0;
int numberOfCharacters = 0;
int numberOfWords = 0;
Scanner scan1 = new Scanner(file);;
while(scan1.hasNextLine()){
StringBuffer sb = new StringBuffer();
String s = scan1.nextLine();
sb.append(s);
numberOfLines++;
numberOfCharacters = numberOfCharacters + s.length();
String words[] = s.split(\" \");
numberOfWords = numberOfWords + words.length;
finalsb.append(sb.reverse());
finalsb.append(\"\ \");
}
System.out.println(\"Number of characters: \"+numberOfCharacters);
System.out.println(\"Number of words: \"+numberOfWords);
System.out.println(\"Number of lines : \"+numberOfLines);
PrintStream ps =new PrintStream(file);
ps.print(finalsb.toString());
ps.flush();
ps.close();
System.out.println(\"Data written to the file \"+fileName);
}
else{
System.out.println(\"File does not exist\");
}
}
}
Output:
Enter file name:
D:\\\\Test1.txt
Number of characters: 0
Number of words: 0
Number of lines : 0
Data written to the file D:\\\\Test1.txt
Test1.txt
tset a si sihT
ereht iH.
Use Java to program the following.1. Create public java class name.pdff3apparelsonline
Use Java to program the following.
1. Create public java class named Benford.
2. It\'s main function should prompt for the name of a data file and then the function iterates
through the all of the elements in the data file and computes the frequency (count and
percentage) of the first number in each entry.
3. Note: Some of the data files have comments that you must filter out.
4. Also note: that blank lines or lines where the number begins or is 0 must also be filtered out.
5. Your output must be formatted as follows.
Solution
Hi Firend, Please find my code.
Please let me know in case of any issue.
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class CountFrequency {
public static void main(String[] args) throws FileNotFoundException {
Scanner sc = new Scanner(System.in);
// taking input file name
System.out.print(\"Enter input file name: \");
String fileName = sc.next();
// opening input file
Scanner inputFile = new Scanner(new File(fileName));
// declaring array to store count of first digit of each entery
int[] frequency = new int[10];
int totalCount = 0; // to maintain total count
int num;
// reading all lines
while(inputFile.hasNextLine()){
// reading current line
String line = inputFile.nextLine();
// if line is not empty
if(line == null || line.isEmpty() || line.trim() == \"\")
continue;
// taking first character of current line
char firstDigit = line.charAt(0);
// if first character is digit and not equal to 0
if(Character.isDigit(firstDigit) && firstDigit != \'0\'){
// converting first character of current line in integer
int d = firstDigit - \'0\';
frequency[d]++;
totalCount++;
}
}
System.out.println(\"Digit\\tCount\\tFrequency\");
for(int i=1; i<=9; i++){
System.out.println(i+\"\\t\"+frequency[i]+\"\\t\"+
((double)frequency[i]/(double)totalCount*100));
}
}
}
/*
Sample run:
##### Entry of input.txt:
453 43
//543
123
0
4ee
875
52
// Output
Enter input file name: input.txt
Digit Count Frequency
1 1 20.0
2 0 0.0
3 0 0.0
4 2 40.0
5 1 20.0
6 0 0.0
7 0 0.0
8 1 20.0
9 0 0.0
*/.
Adjusting primitives for graph : SHORT REPORT / NOTESSubhajit Sahu
Graph algorithms, like PageRank Compressed Sparse Row (CSR) is an adjacency-list based graph representation that is
Multiply with different modes (map)
1. Performance of sequential execution based vs OpenMP based vector multiply.
2. Comparing various launch configs for CUDA based vector multiply.
Sum with different storage types (reduce)
1. Performance of vector element sum using float vs bfloat16 as the storage type.
Sum with different modes (reduce)
1. Performance of sequential execution based vs OpenMP based vector element sum.
2. Performance of memcpy vs in-place based CUDA based vector element sum.
3. Comparing various launch configs for CUDA based vector element sum (memcpy).
4. Comparing various launch configs for CUDA based vector element sum (in-place).
Sum with in-place strategies of CUDA mode (reduce)
1. Comparing various launch configs for CUDA based vector element sum (in-place).
Show drafts
volume_up
Empowering the Data Analytics Ecosystem: A Laser Focus on Value
The data analytics ecosystem thrives when every component functions at its peak, unlocking the true potential of data. Here's a laser focus on key areas for an empowered ecosystem:
1. Democratize Access, Not Data:
Granular Access Controls: Provide users with self-service tools tailored to their specific needs, preventing data overload and misuse.
Data Catalogs: Implement robust data catalogs for easy discovery and understanding of available data sources.
2. Foster Collaboration with Clear Roles:
Data Mesh Architecture: Break down data silos by creating a distributed data ownership model with clear ownership and responsibilities.
Collaborative Workspaces: Utilize interactive platforms where data scientists, analysts, and domain experts can work seamlessly together.
3. Leverage Advanced Analytics Strategically:
AI-powered Automation: Automate repetitive tasks like data cleaning and feature engineering, freeing up data talent for higher-level analysis.
Right-Tool Selection: Strategically choose the most effective advanced analytics techniques (e.g., AI, ML) based on specific business problems.
4. Prioritize Data Quality with Automation:
Automated Data Validation: Implement automated data quality checks to identify and rectify errors at the source, minimizing downstream issues.
Data Lineage Tracking: Track the flow of data throughout the ecosystem, ensuring transparency and facilitating root cause analysis for errors.
5. Cultivate a Data-Driven Mindset:
Metrics-Driven Performance Management: Align KPIs and performance metrics with data-driven insights to ensure actionable decision making.
Data Storytelling Workshops: Equip stakeholders with the skills to translate complex data findings into compelling narratives that drive action.
Benefits of a Precise Ecosystem:
Sharpened Focus: Precise access and clear roles ensure everyone works with the most relevant data, maximizing efficiency.
Actionable Insights: Strategic analytics and automated quality checks lead to more reliable and actionable data insights.
Continuous Improvement: Data-driven performance management fosters a culture of learning and continuous improvement.
Sustainable Growth: Empowered by data, organizations can make informed decisions to drive sustainable growth and innovation.
By focusing on these precise actions, organizations can create an empowered data analytics ecosystem that delivers real value by driving data-driven decisions and maximizing the return on their data investment.
As Europe's leading economic powerhouse and the fourth-largest hashtag#economy globally, Germany stands at the forefront of innovation and industrial might. Renowned for its precision engineering and high-tech sectors, Germany's economic structure is heavily supported by a robust service industry, accounting for approximately 68% of its GDP. This economic clout and strategic geopolitical stance position Germany as a focal point in the global cyber threat landscape.
In the face of escalating global tensions, particularly those emanating from geopolitical disputes with nations like hashtag#Russia and hashtag#China, hashtag#Germany has witnessed a significant uptick in targeted cyber operations. Our analysis indicates a marked increase in hashtag#cyberattack sophistication aimed at critical infrastructure and key industrial sectors. These attacks range from ransomware campaigns to hashtag#AdvancedPersistentThreats (hashtag#APTs), threatening national security and business integrity.
🔑 Key findings include:
🔍 Increased frequency and complexity of cyber threats.
🔍 Escalation of state-sponsored and criminally motivated cyber operations.
🔍 Active dark web exchanges of malicious tools and tactics.
Our comprehensive report delves into these challenges, using a blend of open-source and proprietary data collection techniques. By monitoring activity on critical networks and analyzing attack patterns, our team provides a detailed overview of the threats facing German entities.
This report aims to equip stakeholders across public and private sectors with the knowledge to enhance their defensive strategies, reduce exposure to cyber risks, and reinforce Germany's resilience against cyber threats.
2. File class in Java
Programmers refer to input/output as "I/O".
The File class represents files as objects.
The class is defined in the java.io package.
Creating a File object allows you to get information
about a file on the disk.
Creating a File object does NOT create a new file on
your disk.
File f = new File("example.txt");
if (f.exists() && f.length() > 1000) {
f.delete();
}
2
3. Files
Some methods in the File class:
Method name Description
canRead() returns whether file can be
read
delete() removes file from disk
exists() whether this file exists on disk
getName() returns name of file
length() returns number of characters
in file
renameTo(filename) changes name of file
3
4. Scanner reminder
The Scanner class reads input and processes strings
and numbers from the user.
When constructor is called with System.in, the character
stream is input typed to the console.
Instantiate Scanner by passing the input character
stream to the constructor:
Scanner scan = new Scanner(System.in);
4
5. Scanner reminder
Common methods called on Scanner:
Read a line
String str = scan.nextLine();
Read a string (separated by whitespace)
String str = scan.next( );
Read an integer
int ival = scan.nextInt( );
Read a double
double dval = scan.nextDouble( );
5
6. Opening a file for reading
To read a file, pass a File object as a parameter when
constructing a Scanner
Scanner for a file:
Scanner <name> = new Scanner(new File(<filename>));
Example:
Scanner scan= new Scanner(new File("numbers.txt"));
or:
File file = new File("numbers.txt");
Scanner scan= new Scanner(file);
String variable
or string literal
6
7. File names and paths
relative path: does not specify any top-level folder, so
the path is relative to the current directory:
"names.dat"
"code/Example.java"
absolute path: The complete pathname to a file starting
at the root directory /:
In Linux: ”/users/cs160/programs/Example.java”
In Windows: ”C:/Documents/cs160/programs/data.csv”
7
8. File names and paths
When you construct a File object with a relative path, Java
assumes it is relative to the current directory.
Scanner scan =
new Scanner(new File(”data/input.txt”));
If our program is in ~/workspace/P4
Scanner will look for ~/workspace/P4/data/input.txt
8
9. Compiler error with files
Question: Why will the following program NOT compile?
import java.io.*; // for File
import java.util.*; // for Scanner
public class ReadFile {
public static void main(String[] args) {
File file = new File(“input.txt”);
Scanner scan = new Scanner(file);
String text = scan.next();
System.out.println(text);
}
}
Answer: Because of Java exception handling!
9
10. Compiler error with files
Here is the compilation error that is produced:
ReadFile.java:6: unreported exception
java.io.FileNotFoundException;
must be caught or declared to be thrown
Scanner scan = new Scanner(new File("data.txt"));
The problem has to do with error reporting.
What to do when a file cannot be opened?
File may not exist, or may be protected.
Options: exit program, return error, or throw exception
Exceptions are the normal error mechanism in Java.
10
11. Exceptions
exception: An object that represents a program
error.
Programs with invalid logic will cause exceptions.
Examples:
dividing by zero
calling charAt on a String with an out of range index
trying to read a file that does not exist
We say that a logical error results in an exception
being thrown.
It is also possible to catch (handle) an exception.
11
12. Checked exceptions
checked exception: An error that must be
handled by our program (otherwise it will not
compile).
We must specify what our program will do to handle
any potential file I/O failures.
We must either:
declare that our program will handle ("catch") the exception, or
state that we choose not to handle the exception
(and we accept that the program will crash if an exception
occurs)
12
13. Throwing Exceptions
throws clause: Keywords placed on a method's header
to state that it may generate an exception.
It's like a waiver of liability:
"I hereby agree that this method might throw an exception, and I
accept the consequences (crashing) if this happens.”
General syntax:
public static <type> <name>(<params>) throws <type>
{ … }
When doing file open, we throw IOException.
public static void main(String[] args)
throws IOException {
13
14. Handling Exceptions
When doing file I/O, we use IOException.
public static void main(String[] args) {
try {
File file = new File(“input.txt);
Scanner scan = new Scanner(file);
String firstLine = scan.nextLine();
...
} catch (IOException e) {
System.out.println(“Unable to open input.txt”);
System.exit(-1);
}
}
14
15. Fixing the compiler error
Throwing an exception or handling the exception both
resolve the compiler error.
Throwing Exceptions: User will see program terminate
with exception, that’s not very friendly.
Handling Exceptions: User gets a clear indication of
problem with error message, that’s much better.
We will handle exceptions when reading and writing files
in programming assignments.
15
16. Using Scanner to read file data
Consider a file numbers.txt that contains
this text:
308.2
14.9 7.4 2.8
3.9 4.7 -15.4
2.8
A Scanner views all input as a stream of
characters:
308.2n 14.9 7.4 2.8nnn3.9 4.7 -15.4n2.8n
16
17. Consuming tokens
Each call to next, nextInt, nextDouble, etc.
advances the position of the scanner to the end of the
current token, skipping over any whitespace:
308.2n 14.9 7.4 2.8nnn3.9 4.7 -15.4n2.8n
^
scan.nextDouble();
308.2n 14.9 7.4 2.8nnn3.9 4.7 -15.4n2.8n
^
scan.nextDouble();
308.2n 14.9 7.4 2.8nnn3.9 4.7 -15.4n2.8n
^
17
18. First problem
Write code that reads the first 5 double
values from a file and prints.
18
19. First solution
public static void main(String[] args)
try {
File file = new File(“input.txt”);
Scanner scan = new Scanner(file);
for (int i = 0; i <= 4; i++) {
double next = scan.nextDouble();
System.out.println("number = " + next);
}
} catch (IOException e) {
System.out.println(“Unable to open input.txt”);
System.exit(-1);
}
}
19
21. Second solution
public static void main(String[] args)
try {
File file = new File(“input.txt”);
Scanner scan = new Scanner(file);
while (scan.hasNextDouble() {
double next = scan.nextDouble();
System.out.println("number = " + next);
}
} catch (IOException e) {
System.out.println(“Unable to open input.txt”);
System.exit(-1);
}
}
21
22. Refining the problem
Modify the program again to handle files that
also contain non-numeric tokens.
The program should skip any such tokens.
For example, it should produce the same
output as before when given this input file:
308.2 hello
14.9 7.4 bad stuff 2.8
3.9 4.7 oops -15.4
:-) 2.8 @#*($&
22
23. Refining the program
while (scan.hasNext()) {
if (scan.hasNextDouble()) {
double next = scan.nextDouble();
System.out.println("number = " + next);
} else {
// consume the bad token
scan.next();
}
}
23
24. Reading input line-by-line
Given the following input data:
23 3.14 John Smith "Hello world"
45.2 19
The Scanner can read it line-by-line:
23t3.14 John Smitht"Hello world"ntt45.2 19n
^
scan.nextLine()
23t3.14 John Smitht"Hello world"ntt45.2 19n
^
scan.nextLine()
23t3.14 John Smitht"Hello world"ntt45.2 19n
^
The n character is consumed but not returned.
24
25. File processing question
Write a program that reads a text file and
adds line numbers at the beginning of each
line
25
26. Solution
int count = 0;
while (scan.hasNextLine()) {
String line = scan.nextLine();
System.out.println(count + “ “ + line);
count++;
}
26
27. Problem
Given a file with the following contents:
123 Susan 12.5 8.1 7.6 3.2
456 Brad 4.0 11.6 6.5 2.7 12
789 Jennifer 8.0 8.0 8.0 8.0 7.5
Consider the task of computing hours worked by each
person
Approach:
Break the input into lines.
Break each line into tokens.
27
28. Scanner on strings
A Scanner can tokenize a String, such as a line of a file.
Scanner <name> = new Scanner(<String>);
Example:
String text = "1.4 3.2 hello 9 27.5";
Scanner scan = new Scanner(text);
System.out.println(scan.next()); // 1.4
System.out.println(scan.next()); // 3.2
System.out.println(scan.next()); // hello
28
29. Tokenize an entire file
We can use string Scanner(s) to tokenize each line of
a file:
Scanner scan = new Scanner(new File(<file name));
while (scan.hasNextLine()) {
String line = scan.nextLine();
Scanner lineScan = new Scanner(line);
<process this line...>;
}
29
30. Example
Example: Count the tokens on each line of a file.
Scanner scan = new Scanner(new File("input.txt"));
while (scan.hasNextLine()) {
String line = scan.nextLine();
Scanner lineScan = new Scanner(line);
int count = 0;
while (lineScan.hasNext()) {
String token = lineScan.next();
count++;
}
System.out.println("Line has “+count+" tokens");
}
Input file input.txt:
23 3.14 John Smith "Hello world"
45.2 19
Output to console:
Line has 6 tokens
Line has 2 tokens
30
31. Opening a file for writing
Same story as reading, we must handle exceptions:
public static void main(String[] args) {
try {
File file = new File(“output.txt”);
PrintWriter output = new PrintWriter(file);
output.println(“Integer number: ” + 987654);
...
} catch (IOException e) {
System.out.println(“Unable to write output.txt”);
System.exit(-1);
}
31
32. File output
You can output all the same things as you would with
System.out.println:
Discussion so far has been limited to text files.
output.println(”Double: " + fmt.format(123.456));
output.println("Integer: " + 987654);
output.println("String: " + "Hello There");
Binary files store data as numbers, not characters.
Binary files are not human readable, but more efficient.
32