Storing String from file in an ArrayList object? - java

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Scanner;
public class Cities {
public static void main(String[] args) throws IOException {
String filename;
System.out.println("Enter the file name : ");
Scanner kb = new Scanner(System.in);
filename = kb.next();
//Check if file exists
File f = new File(filename);
if(f.exists()){
//Read file
File myFile = new File(filename);
Scanner inputFile = new Scanner(myFile);
//Create arraylist object
ArrayList<String> list = new ArrayList<String>();
String cit;
while(inputFile.hasNext()){
cit = inputFile.toString();
list.add(inputFile.toString());
}
System.out.println(list);
}else{
System.out.println("File not found!");
}
}
}
I am trying to read a file and add the contents to an arraylist object (.txt file contains strings), but I am totally lost. Any advice?

You should read the file one line by one line and store it to the list.
Here is the code you should replace your while (inputFile.hasNext()):
Scanner input = null;
try
{
ArrayList<String> list = new ArrayList<String>();
input = new Scanner( new File("") );
while ( input.hasNext() )
list.add( input.nextLine() );
}
finally
{
if ( input != null )
input.close();
}
And you should close the Scanner after reading the file.

If you're using Java 7+, then you can use the Files#readAllLines() to do this task for you, instead of you writing a for or a while loop yourself to read the file line-by-line.
File f = new File(filename); // The file from which input is to be read.
ArrayList<String> list = null; // the list into which the lines are to be read
try {
list = Files.readAllLines(f.toPath(), Charset.defaultCharset());
} catch (IOException e) {
// Error, do something
}

You can do it in one single line with Guava.
final List<String> lines = Files.readLines(new File("path"), Charsets.UTF8);
http://docs.guava-libraries.googlecode.com/git/javadoc/com/google/common/io/Files.html#readLines(java.io.File, java.nio.charset.Charset)

Related

Read and Write with java from one file to another

How do I read the following information from a txt file and write just the numbers to another text file using Java? I have it displaying to the console but it will not write to the file also.
Jones 369218658389641
Smith 6011781008881301
Wayne 5551066751345482
Wines 4809134775860430
Biggie 9925689541232325
Luke 7586425896325410
Brandy 4388576018410707
Ryan 2458912425860439
import java.util.Scanner;
import java.io.File;
public class test {
public static void main(String[] args) throws Exception {
// Create a File instance
java.io.File file = new java.io.File("accounts.txt");
// Create a Scanner for the file
Scanner input = new Scanner(file);
// Read data from a file
while (input.hasNext()) {
String accountName = input.next();
Long cardNumber = input.nextLong();
//this is where I want to write just the numbers to a file called cardnums.txt
file = new java.io.File("cardnums.txt");
java.io.PrintWriter output = new java.io.PrintWriter(file);
output.println(cardNumber);
System.out.println(cardNumber);
}
// Close the file
input.close();
}
}
I got it now.
import java.util.Scanner;
import java.io.File;
public class test {
public static void main(String[] args) throws Exception {
// Create a File instance
java.io.File file = new java.io.File("accounts.txt");
// Create a Scanner for the file
Scanner input = new Scanner(file);
// Read data from a file
file = new java.io.File("cardnums.txt");
java.io.PrintWriter output = new java.io.PrintWriter(file);
while (input.hasNext()) {
String accountName = input.next();
Long cardNumber = input.nextLong();
//this is where I want to write just the numbers to a file called credit.txt
output.println(cardNumber);
System.out.println(cardNumber);
}
// Close the file
input.close();
output.flush();
output.close();
}
}
java.io.PrintWriter output = new java.io.PrintWriter(file);
First of all why are you everytime calling this in loop with same filename?
Secondly, once you define it outside loop,
Call flush() on outputstream object and close if not null (preferabbly in finally block) after loop.
if(output!=null) {
output.flush();
output.close();
}
Here's a 1-liner:
Files.write(Paths.get("cardnums.txt"), () ->
Files.lines(Paths.get("accounts.txt"))
.map(s -> s.replaceAll("\\D", ""))
.collect(toList())
.iterator());
Disclaimer: Code may not compile or work as it was thumbed in on my phone (but there's a reasonable chance it will work)

Reading Data file and outputting to another file

Im trying to make a program that reads data from a text file which contains student names and scores they got on a test. I want to output it in this sort of way
Im starting off by trying to read the txt file so I can then re arrange them and then outputting it into another file but im not sure what im doing wrong. Instead it prints into the exe instead of the file I want it to print to.
import java.io.File;
import java.util.Scanner;
public class ReadConsole {
public static void main(String[] args) {
try {
Scanner input = new Scanner(System.in);
System.out.print("Enter the file name with extention : ");
File file = new File(input.nextLine());
input = new Scanner(file); //scans the file
while (input.hasNextLine()) {
String line = input.nextLine();
System.out.println(line);
}
input.close();
} catch (Exception ex) {
ex.printStackTrace();
}
}
}
Click Here for Image
Instead of using System.out PrintStream, you can create a PrintStream that writes to a file:
PrintStream output = new PrintStream(new File("output.txt"));
while (input.hasNextLine()) {
String line = input.nextLine();
output.println(line);
}
Remember to close both input Scanner and output PrintStream:
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter the file name with extention : ");
File file = new File(input.nextLine());
try (Scanner fileInput = new Scanner(file); // scans the file
PrintStream output = new PrintStream(new File("c:/output.txt"))) {
while (input.hasNextLine()) {
String line = input.nextLine();
output.println(line);
}
}
}

Replace string text from a source file, save changes into the original file. Append using StringBuilder

Please consider the following code. I'm not very familiar with StringBuilders or reading/writing data. I need to:
1.) Open source file
2.) Grab words and check for old string, if an old string, then append new string
3.) Use PrintWriter and Close. I am revising the following code below:
import java.io.*;
import java.util.*;
public class ReplaceText {
public static void main(String[] args) throws Exception {
// Check command line parameter usage
if (args.length != 4) {
System.out.println(
"Usage: java ReplaceText sourceFile targetFile oldStr newStr");
System.exit(1);
}
// Check if source file exists
File sourceFile = new File(args[0]);
if (!sourceFile.exists()) {
System.out.println("Source file " + args[0] + " does not exist");
System.exit(2);
}
// Check if target file exists
File targetFile = new File(args[1]);
if (targetFile.exists()) {
System.out.println("Target file " + args[1] + " already exists");
System.exit(3);
}
// Create input and output files
Scanner input = new Scanner(sourceFile);
PrintWriter output = new PrintWriter(targetFile);
while (input.hasNext()) {
String s1 = input.nextLine();
String s2 = s1.replaceAll(args[2], args[3]);
output.println(s2);
}
input.close();
output.close();
}
}
I'd also like to ask the user for the source file, old string, and new string at run time instead of using command line arguments.
I know I still need to incorporate StringBuilder. Here is what I have so far:
public class ReplaceText {
public static void main(String [] args) throws Exception {
Scanner scan = new Scanner(System.in);
System.out.println("What is the source file");
java.io.File file = new java.io.File(scan.next());
System.out.println("Enter old line");
String oldLine = scan.nextLine();
System.out.println("Enter new line");
String newLine = scan.nextLine();
//scan.exit;
/** Read one line at a time, append, replace oldLine with
* newLine using a loop */
//Scanner scan2 = new Scanner(file);
//PrintWriter that replaces file
java.io.PrintWriter output = new java.io.PrintWriter(file);
output.println(file);
output.close();
}
}

Reading two files and then finding the growth rate

I need help trying to read two files that have the census from 2010 and 2000. I have to read both files and then find out the population growth between those two files. I keep getting null for ever single state. I know that I have null for inLine1 and inLine2.
The file looks like this
Alabama,4779736
Alaska,710231
Arizona,6392017
Arkansas,2915918
Code:
import java.util.ArrayList;
import java.util.Scanner;
import java.io.*;
public class pa10
{
public static void main(String[] args, char[] inLine2, char[] inLine1)
throws java.io.IOException
{
String fileName1 = "Census2000growth.txt";
String fileName2 = "Census2010growth.txt";
int i;
File f = new File("Census2010growth.txt");
if(!f.exists()) {
System.out.println( "file does not exist ");
}
Scanner infile = new Scanner(f);
infile.useDelimiter ("[\t|,|\n|\r]+"); //create a delimiter
final int MAX = 51;
int [] myarray = new int [MAX];
String[] statearray = new String[MAX];
int fillsize;
// set up input stream1
FileReader fr1 = new
FileReader(fileName1);
// buffer the input stream
BufferedReader br1 =
new BufferedReader(fr1);
// set up input stream2
FileReader fr2 = new
FileReader(fileName2);
// buffer the input stream
BufferedReader br2 =
new BufferedReader(fr2);
// read and display1
String buffer1 = "";
ArrayList<String> firstFile1 = new ArrayList<String>();
while ((buffer1 = br1.readLine()) != null) {
firstFile1.add(buffer1);
System.out.println(inLine1); // display the line
}
br1.close();
//Now read the second file or make for this separate method
// read and display2
String buffer2 = "";
ArrayList<String> firstFile2 = new ArrayList<String>();
while ((buffer2 = br2.readLine()) != null) {
firstFile2.add(buffer2);
System.out.println(inLine2); // display the line
}
br2.close();
//Read all the lines in array or list
//After that you can calculate them.
}
}
Read the BufferedReader documentation. Your file isn't formatted with the types of line separators it is expecting. I suggest using a Scanner and setting the line separator to the appropriate pattern, or using String.split
You have two different variables, buffer1 and inline1. Since you never set the value of inline1, it will always be null.

Basic File Reading to Array Storage

I have a simple Java questions and I need a simple answer, if possible. I need to input the data from the file and store the data into an array. To do this, I will have to have the program open the data file, count the number of elements in the file, close the file, initialize your array, reopen the file and load the data into the array. I am mainly having trouble getting the file data stored as an array. Here's what I have:
The to read file is here: https://www.dropbox.com/s/0ylb3iloj9af7qz/scores.txt
import java.io.*;
import java.util.*;
import javax.swing.*;
import java.text.*;
public class StandardizedScore8
{
//Accounting for a potential exception and exception subclasses
public static void main(String[] args) throws IOException
{
// TODO a LOT
String filename;
int i=0;
Scanner scan = new Scanner(System.in);
System.out.println("\nEnter the file name:");
filename=scan.nextLine();
File file = new File(filename);
//File file = new File ("scores.txt");
Scanner inputFile = new Scanner (file);
String [] fileArray = new String [filename];
//Scanner inFile = new Scanner (new File ("scores.txt"));
//User-input
// System.out.println("Reading from 'scores.txt'");
// System.out.println("\nEnter the file name:");
// filename=scan.nextLine();
//File-naming/retrieving
// File file = new File(filename);
// Scanner inputFile = new Scanner(file);
I recommend you use a Collection. This way, you don't have to know the size of the file beforehand and you'll read it only once, not twice. The Collection will manage its own size.
Yes, you can if you don't care about the trouble of doing things twice. Use while(inputFile.hasNext()) i++;
to count the number of elements and create an array:
String[] scores = new String[i];
If you do care, use a list instead of an array:
List<String> list = new ArrayList<String>();
while(inputFile.hasNext()) list.add(inputFile.next());
You can get list elements like list.get(i), set list element like list.set(i,"string") and get the length of list list.size().
By the way, your line of String [] fileArray = new String [filename];is incorrect. You need to use an int to create an array instead of a String.
/*
* Do it the easy way using a List
*
*/
public static void main(String[] args) throws IOException
{
Scanner scan = new Scanner(System.in);
System.out.println("\nEnter the file name:");
String filename = scan.nextLine();
FileReader fileReader = new FileReader(filename);
BufferedReader reader = new BufferedReader(fileReader);
List<String> lineList = new ArrayList<String>();
String thisLine = reader.readLine();
while (thisLine != null) {
lineList.add(thisLine);
thisLine = reader.readLine();
}
// test it
int i = 0;
for (String testLine : lineList) {
System.out.println("Line " + i + ": " + testLine);
i++;
}
}
We can use the ArrayList collection to store the values from the file to the array without knowing the size of the array before hand.
You can get more info on ArrayList collections from the following urls.
http://docs.oracle.com/javase/tutorial/collections/implementations/index.html
http://www.java-samples.com/showtutorial.php?tutorialid=234

Categories