I have an assignment that ask me to read from a file, us an ArrayList to organize and declare the numbers, and then calculate the average of those numbers and print them in a new file. I know that I need 3 parts for this which would be the Reader, Writer and the Array List but i get an error when compiling when I try to read from the scaner. Can someone help with how to read from the file with the ArrayList and likewise, how to write into a new file.
import java.util.ArrayList;
import java.util.Collections;
import java.io.*; //Replaces the scanner
import java.io.BufferedReader;
import java.util.Scanner;
import java.io.FileReader; // Used by the BufferedReader import java.util.Scanner;
import java.io.FileNotFoundException; //
import java.io.IOException; //
class SD9 {
public static void main( String[] args ) {
try{
FileReader Fr = new FileReader( "Patriots.txt" );
// the file reader bridges the program and the .txt file together.
BufferedReader Br = new BufferedReader( Fr );
String line = Br.readLine();
// BufferredReaders can only read one line at a time.
FileWriter fw = new FileWriter( "PatriotsStat.txt" );
BufferedWriter bw = new BufferedWriter( fw );
while( line != null ) {
//BufferredReaders return null once they've reached the end of the file.
ArrayList<Double> Patriots = new ArrayList<Double>();
for(int i = 0; i < 23; ++i ) {
Patriots.add( scan.nextDouble() );
}
/* String Line1 = "2014 PreSeason:";
bw.write( " " );
bw.newLine();
/*String Line3 = " FinalAvg: " + finalAvg;
bw.write( Line3 );
bw.newLine();*/
}
bw.close();
}catch( FileNotFoundException F ) {
//.....
} catch( IOException I ) {
}
}
}
This should work:
import java.io.File;
import java.io.FileNotFoundException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Scanner;
class SD9 {
public static void main(String[] args) throws FileNotFoundException {
Scanner scanner = new Scanner(new File("Patriots.txt"));
PrintWriter writer = new PrintWriter(new File("PatriotsStat.txt"));
ArrayList<Double> Patriots = new ArrayList<Double>();
double sum = 0;
while (scanner.hasNext()) {
double num = scanner.nextDouble();
sum += num;
Patriots.add(num);
}
scanner.close();
for (int i = 0; i < Patriots.size(); i++) {
writer.write(Patriots.get(i)+"\n");
}
double average = sum / Patriots.size();
writer.write("Average : "+average);
writer.close();
}
}
I believe this will help.
File fr = new File("Patriots.txt");
Scanner sc = new Scanner(fr);
ArrayList<Double> patriots = new ArrayList<Double>();
while(sc.hasNextDouble()){
patriots.add(sc.nextDouble);
}
sc.close();
The code is failing to compile because your code does not follow the correct Java syntax for a try...catch block
In Java, a try...catch block follows the following form:
try {
// do something...
} catch (Exception e) {
// handle the exception...
}
In your code, you will see that you have code in between your try block and your catch block:
The bw.close() line is the culprit.
try {
// code
}
bw.close();
} catch( FileNotFoundException F ) {
//.....
} catch( IOException I ) {
}
Assuming you are doing this in an IDE (NetBeans, Eclipse, etc.), this relevant information can be found in the 'Build Output' window
Related
In a file of randomly generated passwords my goal is to ask for a password, check the 'codes.txt' file to see if it exists, say 'LOGIN COMPLETE' for 5 seconds, delete the password, then close the files. When I reach the while loop I nothing works the way I need it to. It has all kinds of different results in various situation, none of which I can understand. I haven't even figured out how to delete the stuff on the console after 5 seconds have passed printing 'LOGIN COMPLETE'. If anybody could help me right now I would really appreciate it. My code is located below.
package password;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Random;
import java.util.Scanner;
public class Password {
public void creator() throws IOException {
FileWriter fw = new FileWriter(new File("codes.txt"));
PrintWriter out = new PrintWriter(fw);
char[] chars = "abcdefghijklmnopqrstuvwxyz1234567890".toCharArray();
Random random = new Random();
for (int x = 0; x < 51; x++){
String word = "";
for (int i = 0; i <= 10; i++) {
char c = chars[random.nextInt(chars.length)];
word+=c;
}
out.println(word);
}
fw.close();
}
public void readit() throws FileNotFoundException, InterruptedException {
File file = new File("codes.txt");
Scanner input = new Scanner(file);
//prints each line in the file
while (input.hasNextLine()) {
String line = input.nextLine();
System.out.println(line);
}
Thread.sleep(10000);
input.close();
}
public void checkit() throws FileNotFoundException, IOException, InterruptedException {
File checkFile = new File("codes.txt");
File tempFile = new File("tempFile.txt");
Scanner input = new Scanner(System.in);
Scanner reader = new Scanner(checkFile);
FileWriter fw = new FileWriter(tempFile);
PrintWriter out = new PrintWriter(fw);
System.out.println("What is the password?");
String word = input.nextLine();
while(reader.hasNextLine()) {
String line = input.nextLine();
if(line.equals(word)){
System.out.println("LOGIN COMPLETE");
Thread.sleep(5000);
} else {
out.println(line);
}
}
reader.close();
fw.close();
checkFile.delete();
tempFile.renameTo(checkFile);
}
}
The main file is below.
package password;
import java.io.FileNotFoundException;
import java.io.IOException;
public class Main {
public static void main(String[] args) throws IOException, FileNotFoundException, InterruptedException {
Password pass = new Password();
pass.creator();
pass.readit();
pass.checkit();
}
}
I am a beginner at java so in order for me to understand the code please use simple beginners code.
In the end I've decided there isn't really a need to clear the console screen in Netbeans, and I'll just leave it as is. I do want to give the solution I got in the end for those confused on what I wanted and for anyone who might have the same problems as I did.
package password;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Random;
import java.util.Scanner;
public class Password {
//Makes 50 random passwords(ten characters using letters and numbers)
public void creator() throws IOException {
FileWriter fw = new FileWriter(new File("codes.txt"));
PrintWriter out = new PrintWriter(fw);
char[] chars = "abcdefghijklmnopqrstuvwxyz1234567890".toCharArray();
Random random = new Random();
for (int x = 0; x < 51; x++){
String word = "";
for (int i = 0; i <= 10; i++) {
char c = chars[random.nextInt(chars.length)];
word+=c;
}
out.println(word);
}
fw.close();
}
//prints passwords for 10 seconds
public void readit() throws FileNotFoundException, InterruptedException {
File file = new File("codes.txt");
Scanner input = new Scanner(file);
//prints each line in the file
while (input.hasNextLine()) {
String line = input.nextLine();
System.out.println(line);
}
Thread.sleep(10000);
input.close();
}
//asks for password and if it's correct then states LOGIN COMPLETE and then adds exceptions to a temporary file then readds to main file then closes
public void checkit() throws FileNotFoundException, IOException, InterruptedException {
File file = new File("codes.txt");
FileWriter fw = new FileWriter(new File("code.txt"));
PrintWriter out = new PrintWriter(fw);
Scanner reader = new Scanner(file);
Scanner input = new Scanner(System.in);
System.out.println("Enter a password");
String word = input.nextLine();
//prints each line in the file
while (reader.hasNextLine()) {
String line = reader.nextLine();
if (line.equals(word)) {
System.out.println("LOGIN COMPLETE");
Thread.sleep(5000);
} else {
out.println(line);
}
}
reader.close();
fw.close();
File file2 = new File("code.txt");
Scanner reader2 = new Scanner(file2);
FileWriter fw2 = new FileWriter(new File("codes.txt"));
PrintWriter out2 = new PrintWriter(fw2);
while (reader2.hasNextLine()) {
String line = reader2.nextLine();
out2.println(line);
}
file2.delete();
fw2.close();
System.exit(0);
}
}
Main File Below:
package password;
import java.io.FileNotFoundException;
import java.io.IOException;
public class Main {
public static void main(String[] args) throws IOException, FileNotFoundException, InterruptedException {
Password pass = new Password();
pass.creator();
pass.readit();
pass.checkit();
}
}
I have to create a file named Lab13.txt. In the file I have 10 numbers. I import the 10 numbers and have to Multiply all the numbers from Lab13.txt by 10 and save all the new numbers a new file named Lab13_scale.txt. so if the number 10 is in lab13.txt it prints 100 to Lab13_scale.txt. Here is what
I have:
import java.io.*;
import java.util.Scanner;
public class lab13 {
public static void main(String[] args) throws IOException{
File temp = new File("Lab13.txt");
Scanner file= new Scanner(temp);
PrintWriter writer = new PrintWriter("Lab13_scale.txt", "UTF-8");
writer.println("");
writer.close();
}
}
How do I multiply the numbers by 10 and export it to the new file?
This code is simple as this:
import java.io.File;
import java.io.FileNotFoundException;
import java.io.PrintWriter;
import java.util.Scanner;
public class Lab13 {
public static void main(String[] args) throws FileNotFoundException {
Scanner scan = new Scanner(new File("Lab13.txt"));
PrintWriter print = new PrintWriter(new File("Lab13_scale.txt"));
while(scan.hasNext()){
print.write(10 * scan.nextInt()+"\n");
}
print.close();
scan.close();
}
}
If the numbers are separated by spaces, use
file.nextInt();
Full Code:
int[] nums = new int[10];
for(int i = 0; i < 10; i++){
nums[i] = file.nextInt();
nums[i] *= 10;
}
after writer.println("");
for(int i = 0; i < 10; i++){
writer.println(nums[i]);
}
I'll give you a different approach. I have wrote this from memory, let me know if you have any errors. I assumed the numbers are one on each line.
public static void main(String[] args)
{
String toWrite = "";
try{
String line;
BufferedReader reader = new BufferedReader(new FileReader("Lab13.txt"));
while((line = reader.readLine())!=null){
int x = Integer.parseInt(line);
toWrite += (x*10) + "\n";
}
File output = new File("lab13_scale.txt");
if(!output.exists()) output.createNewFile();
FileWriter writer = new FileWriter(output.getAbsoluteFile());
BufferedWriter bWriter= new BufferedWriter(writer);
bWriter.write(toWrite);
bWriter.close();
}catch(Exception e){}
}
Can anyone show me a basic guideline for how to do this sort of thing? Would you use an Array or an ArrayList, and why? Anything else I've found online is too complicated to understand for my level of experience with Java. The file is a simple text file with seven decimal values per line, and contains three lines. Here is what I have so far and am just testing it to see if I'm doing the ArrayList properly. It keeps printing an empty ArrayList that is just two brackets.
import java.io.File;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.Scanner;
public class SalesAnalysis
{
public static void main (String[] args) throws FileNotFoundException
{
Scanner salesDataFile = new Scanner(new File("SalesData.txt"));
ArrayList<Double> salesData = new ArrayList<Double>();
while(salesDataFile.hasNextDouble())
{
salesData.add(salesDataFile.nextDouble());
}
salesDataFile.close();
System.out.println(salesData);
}
}
import java.io.File;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.Scanner;
public class SalesAnalysis
{
public static void main (String[] args) throws FileNotFoundException
{
Scanner salesDataFile = new Scanner(new File("SalesData.txt"));
ArrayList<Double> salesData = new ArrayList<Double>();
while(salesDataFile.hasNextLine()){
String line = salesDataFile.nextLine();
Scanner scanner = new Scanner(line);
scanner.useDelimiter(",");
while(scanner.hasNextDouble()){
salesData.add(scanner.nextDouble());
}
scanner.close();
}
salesDataFile.close();
System.out.println(salesData);
}
}
Read lines from file, then for each file get doubles using Scanner.
And for per line basis, you can just create Lists for every line, like:
import java.io.File;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.Scanner;
public class SalesAnalysis
{
public static void main (String[] args) throws FileNotFoundException
{
Scanner salesDataFile = new Scanner(new File("SalesData.txt"));
while(salesDataFile.hasNextLine()){
String line = salesDataFile.nextLine();
ArrayList<Double> salesData = new ArrayList<Double>();
Scanner scanner = new Scanner(line);
scanner.useDelimiter(",");
while(scanner.hasNextDouble()){
salesData.add(scanner.nextDouble());
}
scanner.close();
System.out.println(salesData);
}
salesDataFile.close();
}
}
As you are getting per line values inside first while() loop, you can do whatever with line.
// number of values in file
int totalNumValues = 0;
// total sum
double totalSum = 0;
while(salesDataFile.hasNextLine()){
String line = salesDataFile.nextLine();
ArrayList<Double> salesData = new ArrayList<Double>();
// total values in this line
int numValuesInLine = 0;
// sum in this line
double sumLine = 0;
Scanner scanner = new Scanner(line);
scanner.useDelimiter(",");
while(scanner.hasNextDouble()){
double value = scanner.nextDouble();
sumLine = sumLine + value;
numValuesInLine++;
totalNumValues++;
totalSum = totalSum + value;
}
scanner.close();
System.out.println(salesData);
}
I'd do something like this:
Scanner salesDataFile = new Scanner(new File("SalesData.txt"));
ArrayList<ArrayList< double > > salesData = new ArrayList<>();
while(salesDataFile.hasNextLine() )
{
String stringOfNumbers[] = salesDataFile.nextLine().split(",");
ArrayList< double > aux = new ArrayList<>( stringOfNumbers.length );
for( int i = 0; i < stringOfNumbers.length; ++i )
aux.get(i) = Double.parseDouble( stringOfNumbers[i] );
//... Perform your row calculations ...
salesData.add( aux );
}
salesDataFile.close();
System.out.println(salesData);
As #Justin Jasmann said, you have comma separated values, so technically they are more than just double values, why not read them as String and then parse them using Double.parseDouble(String s) after you have your comma separatad value by using string.split(","); on every line.
This is what you are looking for,
import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.text.NumberFormat;
import java.text.ParseException;
import java.text.ParsePosition;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
public class FileRead {
public static void main(String args[])
{
try{
// Open the file that is the first
FileInputStream fstream = new FileInputStream("textfile.txt");
// Use DataInputStream to read binary NOT text.
BufferedReader br = new BufferedReader(new InputStreamReader(fstream));
String strLine;
List<Double> saleNumbers= new ArrayList<Double>();
//Read File Line By Line
while ((strLine = br.readLine()) != null) {
// Add number from file to list
saleNumbers.add( parseDecimal(strLine));
}
//Close the input stream
in.close();
System.out.println(saleNumbers);
}catch (Exception e){
e.printStackTrace();
}
}
public static double parseDecimal(String input) throws NullPointerException, ParseException{
if(input == null){
throw new NullPointerException();
}
input = input.trim();
NumberFormat numberFormat = NumberFormat.getNumberInstance(Locale.US);
ParsePosition parsePosition = new ParsePosition(0);
Number number = numberFormat.parse(input, parsePosition);
if(parsePosition.getIndex() != input.length()){
throw new ParseException("Invalid input", parsePosition.getIndex());
}
return number.doubleValue();
}
}
I have a text file with the following contents:
public class MyC{
public void MyMethod()
{
System.out.println("My method has been accessed");
System.out.println("hi");
}
}
I have an array num[]= {2,3,4}; which contains the line numbers to be completely replaced with the strings from this array
String[] VALUES = new String[] {"AB","BC","CD"};
That is line 2 will be replaced with AB, line 3 with BD and ine 4 with CD.
Lines which are not in the num[]array have to be written to a new file along with the changes made.
I have this so far.I tried several kind of loops but still it does not work.
public class ReadFileandReplace {
/**
* #param args
*/
public static void main(String[] args) {
try {
int num[] = {3,4,5};
String[] VALUES = new String[] {"AB","BC","CD"};
int l = num.length;
FileInputStream fs= new FileInputStream("C:\\Users\\Antish\\Desktop\\Test_File.txt");
BufferedReader br = new BufferedReader(new InputStreamReader(fs));
LineNumberReader reader = new LineNumberReader(br);
FileWriter writer1 = new FileWriter("C:\\Users\\Antish\\Desktop\\Test_File1.txt");
String line;
int count =0;
line = br.readLine();
count++;
while(line!=null){
System.out.println(count+": "+line);
line = br.readLine();
count++;
int i=0;
if(count==num[i]){
int j=0;;
System.out.println(count);
String newtext = line.replace(line, VALUES[j]) + System.lineSeparator();
j++;
writer1.write(newtext);
}
i++;
writer1.append(line);
}
writer1.close();
}
catch (IOException e) {
e.printStackTrace();
} finally {
}
}
}
The expected output should look like this:
public class MyC{
AB
BC
CD
Sys.out.println("hi");
}
}
When I run the code, all lines appear on the same line.
You've done almost, I've updated your code with a map. Check this
int num[] = {3, 4, 5};
String[] values = new String[]{"AB", "BC", "CD"};
HashMap<Integer,String> lineValueMap = new HashMap();
for(int i=0 ;i<num.length ; i++) {
lineValueMap.put(num[i],values[i]);
}
FileInputStream fs = new FileInputStream("test.txt");
BufferedReader br = new BufferedReader(new InputStreamReader(fs));
FileWriter writer1 = new FileWriter("test1.txt");
int count = 1;
String line = br.readLine();
while (line != null) {
String replaceValue = lineValueMap.get(count);
if(replaceValue != null) {
writer1.write(replaceValue);
} else {
writer1.write(line);
}
writer1.write(System.getProperty("line.separator"));
line = br.readLine();
count++;
}
writer1.flush();
You're appending each line to the same string. You should add the line separator character at the end of each line as well. (You can do this robustly using System.getProperty("line.separator"))
you have not appended end line character.
writer1.append(line); is appending the data in line without endline character. Thus it is showing in one line. You might need to change it to:
writer1.append(line).append("\n");
Try This
package src;
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.FileWriter;
import java.io.InputStreamReader;
import java.io.LineNumberReader;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.TimeZone;
public class MainTest {
static int i ;
public static void main(String[] arg)
{
try {
int num[] = {3,4,5};
String[] VALUES = new String[] {"AB","BC","CD"};
FileInputStream fs= new FileInputStream("C:\\Test\\ren.txt");
BufferedReader br = new BufferedReader(new InputStreamReader(fs));
FileWriter writer1 = new FileWriter("C:\\Test\\ren1.txt");
String line;
Integer count =0;
line = br.readLine();
count++;
while(line!=null){
for(int index =0;index<num.length;index++){
if(count == num[index]){
line = VALUES[index];
}
}
writer1.write(line+System.getProperty("line.separator"));
line = br.readLine();
count++;
}
writer1.close();
}
catch (Exception e) {
e.printStackTrace();
} finally {
}
}
}
I have got a file containing a large amount of numbers.
I have tried to use the following code to read it from the file, but it is super slow anyone can help to reduce the time?
Following is my code to read it in a very slow way:
import java.io.BufferedInputStream;
import java.io.DataInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.*;
public class FileInput {
public static void main(String[] args) {
Scanner scan1 = new Scanner(System.in);
String filename = scan1.nextLine();
File file = new File(filename);
FileInputStream fis = null;
BufferedInputStream bis = null;
DataInputStream dis = null;
try {
fis = new FileInputStream(file);
bis = new BufferedInputStream(fis);
dis = new DataInputStream(bis);
while (dis.available() != 0) {
System.out.println(dis.readLine());
}
fis.close();
bis.close();
dis.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
Don't use a DataInputStream to read lines from a file. Instead, use a BufferedReader, as in:
fis = new FileInputStream(file);
BufferedReader reader = new BufferedReader(new InputStreamReader(fis));
while ((String line = reader.readLine()) != null) {
System.out.println(line);
}
The javadoc on DataInputStream.readLine tells you to not use that method. (it's been deprecated)
Of course, when you actually get around to reading the numbers, I'd encourage you to forget reading the lines yourself, and just let Scanner read the numbers for you. If you need to know which numbers were on the same line, Scanner can do that for you too:
Scanner fileScanner = new Scanner(file, "UTF-8").useDelimiter(" +| *(?=\\n)|(?<=\\n) *");
while (fileScanner.hasNext()) {
List<Integer> numbersOnLine = new ArrayList<Integer>();
while (fileScanner.hasNextInt()) {
numbersOnLine.add(fileScanner.nextInt());
}
processLineOfNumbers(numbersOnLine);
if (fileScanner.hasNext()) {
fileScanner.next(); // clear the newline
}
}
That fancy regex makes it so that the newline characters between lines also show up as tokens to the Scanner.
It runs much faster on my machine with the println is commented out. Writing to the screen slows things down a lot. And that's not just a java thing...happens in C/C++ and every other language I've worked with.
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.util.Scanner;
public class file {
public static void main(String[] args){
Scanner keyboard = new Scanner(System.in);
String fname = "";
System.out.print("File Name: ");
fname = keyboard.next();
try{
Scanner file1 = new Scanner(new FileReader(fname));
System.out.println("File Open Successful");
int length = file1.nextInt();
String[] content = new String[length];
for (int i=0;i<length;i++){
content[i] = file1.next();
}
for (int i=0;i<length;i++){
System.out.println("["+i+"] "+content[i]);
}
System.out.println("End of file.");
} catch (FileNotFoundException e){
System.out.println("File Not Found!");
}
}
}