File I/O Practice. - java

I'm trying to take names from a file called boysNames.txt . That contains 1000 boy names. for Example every line looks like this in the file looks like this:
Devan
Chris
Tom
The goal was just trying to read in the name, but I couldn't find a method in the java.util package that allowed me to grab just the name in the file boysName.txt .
For example I just wanted to grab Devan, then next Chris, and tom.
NOT "1. Devan" and "2. Chris."
The problem is hasNextLine grabs the whole line. I don't want the "1." part.
So I just want Devan, Chris, Tom to be read or stored in a variable of type String. Does anyone know how to do that? I've tried HasNext(), but that didn't work.
Here the code here so you can get a visual:
import java.io.PrintWriter;
import java.io.FileOutputStream;
import java.io.FileNotFoundException;
import java.util.Scanner;
import java.io.FileInputStream;
public class PracticeWithTxtFiles {
public static void main(String[] args){
PrintWriter outputStream = null;
Scanner inputStream = null;
try{
outputStream = new PrintWriter(new FileOutputStream("boys.txt")); //opens up the file boys.txt
inputStream = new Scanner(new FileInputStream("boyNames.txt"));//opens up the file boyNames.txt
}catch(FileNotFoundException e){
System.out.println("Problem opening/creating files");
System.exit(0);
}
String names = null;
int ssnumbers= 0;
while(inputStream.hasNextLine())//problem is right here need it to just
// grab String representation of String, not an int
{
names = inputStream.nextLine();
ssnumbers++;
outputStream.println(names + " " + ssnumbers);
}
inputStream.close();
outputStream.close();
}
}

If you are unaware, Check for this String API's Replace method
String - Library
Just do a replace, its as simple as that.
names = names.replace(".","").replaceAll("[0-9]+","").trim()

Related

How to gets numbers from txt file and than parse to integer?

I use Android Studio.I have a text file with some of numbers and I want to calculate them with others numbers. When I am try to convert them from string with method Integer.parseInt on program start I get error and program close.Error is :
at java.lang.Integer.parseInt(Integer.java:521)
at java.lang.Integer.parseInt(Integer.java:556)
I am just beginner and sorry for bad english , I hope you understand my problem.
This is part of my code.
public void read (){
try {
FileInputStream fileInput = openFileInput("example.txt");
InputStreamReader reader = new InputStreamReader(fileInput);
BufferedReader buffer = new BufferedReader(reader);
StringBuffer strBuffer = new StringBuffer();
String lines;
while ((lines = buffer.readLine()) != null) {
strBuffer.append(lines + "\n");
}
int numbers = Integer.parseInt(strBuffer.toString());
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
Here:
int numbers = Integer.parseInt(strBuffer.toString());
You should read the javadoc for the library methods you are using. parseInt() parses one number from a string that contains one number.
So you need
to learn how to use arrays of int (because you want to read and process multiple numbers), not just a single one
to then use parseInt() on the individual number strings in that file
Also note that you can use the Scanner to directly work on an InputStream, there is no need to first turn the complete file content into one large string in memory!
Integer.parseInt(String) throws a NumberFormatException when its argument can't be converted to a number.
Break your problem into smaller, more manageable blocks. Your code currently gets the entire content of example.txt and tries to parse the whole thing to an Integer.
One possibility for reading all integer values is to do this with a java.util.Scanner object instead and use its nextInt() method.
Consider the following example, given a file example.txt with integers separated by spaces.
import java.io.File;
import java.io.InputStream;
import java.nio.file.Files;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
public class App {
public static void main(String...args) throws Exception {
File file = new File("/home/william/example.txt");
try (InputStream is = Files.newInputStream(file.toPath())) {
Scanner scanner = new Scanner(is);
List<Integer> ints = new ArrayList<>();
while (scanner.hasNextInt()) {
int i = scanner.nextInt();
System.out.printf("Read %d%n", i);
ints.add(i);
}
}
}
}

reading/writing variables from text files to variables

I need to make a system for storing customer information and all quotations to an external file as well as entering more customers, listing customers, and the same with the quotations. As well as this I need to link all quotations/customers to an ID. I basically need to do SQL in java. However, I really need help with my input and output system, and writing all info to an array. I have got two main pieces of code but they are very inefficient and I need some suggestions, improvements or an entirely different system.
Input from file Code:
import java.io.*; //import classes
import java.util.ArrayList;
import java.util.Iterator;
public class MyTextReader{
public static void main(String[] args){
String myDirectory = System.getProperty("user.dir");
String fullDirectory = myDirectory + "\\myText.txt";
String input_line = null;
ArrayList<String> textItems = new ArrayList<String>(); //create array list
try{
BufferedReader re = new BufferedReader(new FileReader(fullDirectory));
while((input_line = re.readLine()) != null){
textItems.add(input_line); //add item to array list
}
}catch(Exception ex){
System.out.println("Error: " + ex);
}
Iterator myIteration = textItems.iterator(); //use Iterator to cycle list
while(myIteration.hasNext()){ //while items exist
System.out.println(myIteration.next()); //print item to command-line
}
}
}
Output to File
import java.io.FileWriter; //import classes
import java.io.PrintWriter;
public class MyTextWriter{
public static void main(String[] args){
FileWriter writeObj; //declare variables (uninstantiated)
PrintWriter printObj;
String myText = "Hello Text file";
try{ //risky behaviour – catch any errors
writeObj = new FileWriter("C:\\Documents\\myText.txt" , true);
printObj = new PrintWriter(writeObj);//create both objects
printObj.println(myText); //print to file
printObj.close(); //close stream
}catch(Exception ex){
System.out.println("Error: " + ex);
}
}
}
For reading text from a file
FileReader fr = new FileReader("YourFile.txt");
BufferedReader br = new BufferedReader(fr);
String s="";
s=br.readLine();
System.out.println(s);
For Writting Text to file
PrintWriter writeText = new PrintWriter("YourFile.txt", "UTF-8");
writeText.println("The first line");
writeText.println("The second line");
writeText.close();

Java: Having trouble reading from a file

import java.io.FileReader;
import java.io.FileWriter;
import java.io.BufferedReader;
import java.io.PrintWriter;
import java.io.IOException;
public class TextFile {
private static void doReadWriteTextFile() {
try {
// input/output file names
String inputFileName = "README_InputFile.rtf";
// Create FileReader Object
FileReader inputFileReader = new FileReader(inputFileName);
// Create Buffered/PrintWriter Objects
BufferedReader inputStream = new BufferedReader(inputFileReader);
while ((inLine = inputStream.readLine()) != null) {
System.out.println(inLine);
}
inputStream.close();
} catch (IOException e) {
System.out.println("IOException:");
e.printStackTrace();
}
}
public static void main(String[] args) {
doReadTextFile();
}
}
I'm just learning Java, so take it easy on me. My program's objective is to read a text file and output it into another text file in reverse order. The problem is the professor taught us to to deal with strings and reverse it and such, but nothing about importing/exporting files. Instead, he gave us the following sample code which should import a file. The file returns 3 errors: The first two deal with inLine not being a symbol on lines 24 and 25. The last cannot find the symbol doReadTextFile on line 40.
I have no idea how to read this file and make the necessary changes to reverse and output into a new file. Any help is hugely appreciated.
I also had to change the file type from .txt to .rtf. I'm not sure if that affects how I need to go about this.
EDIT I defined inLine and fixed the doReadWritetextFile naming error, which fixed all my compiling errors. Any help on outputting into new file still appreciated!
I'm also aware he gave me bad sample code. It's supposed to be so we can learn troubleshooting, but with no working code to go off of and very extremely knowledge of the language, it's very difficult to see what's wrong. Thanks for the help!
The good practice will be to use a BufferedFileReader
BufferedFileReader bf = new BufferedFileReader(new FileReader(new File("your_file.your_extention")));
Then you can read lines in your file :
// Initilisation of the inLine variable...
String inLine = null;
while((inLine = bf.readLine()) != null){
System.out.println(inLine);
}
To output a file, you can use StringBuilder to hold the file contents:
private static void doReadWriteTextFile()
{
....
StringBuilder sb = new StringBuilder();
while ((inLine = inputStream.readLine()) != null)
{
sb.append(inline);
}
FileWriter writer = new FileWriter(new File("C:\\temp\\test.txt"));
BufferedWriter bw = new BufferedWriter(writer);
w.write(sb.toString());
bw.close();
}

Reading files in Java vs. Python

I am currently learning Java for an intro CS class. I have beginner experience with Python, which I learned from the eTextbook Learn Python the Hard Way (http://learnpythonthehardway.org/book/).
I am learning Java by converting the Python source in the book to Java source.
I am stuck on opening and reading files in Java. I want to convert this Python code (exercise 15 in the book) to Java:
from sys import argv
script, filename = argv
txt = open(filename)
print "Here's your file %r:" % filename
print txt.read()
print "Type the filename again:"
file_again = raw_input("> ")
txt_again = open(file_again)
print txt_again.read()
This is what I have for opening the file in Java:
System.out.println("Type the filename again: ");
Scanner in = new Scanner(System.in);
String file_name = in.nextLine();
try
{
Scanner txt_again = new Scanner(new File(file_again));
}
catch ( IOException e)
{
System.out.println("Sorry but I was unable to open your file");
e.printStackTrace();
System.exit(0);
}
How do I output the opened file (a text file)? Also, how do I add arguments (i.e. script, filename) in Java?
For reading files I would suggest following this site: Read File With Java.
As for arguments, I'm not sure if you mean into the program itself (command line arguments) or are talking about more input with the scanner. If you are talking about command line arguments, I would follow the Oracle Docs.
Good luck.
If you insist on using scanner, here is the code
// Read each line in the file
while(txt_again.hasNext()) {
// Read each line and display its value
System.out.println("First line: " + txt_again.nextLine());
// String whole_txt = whole_txt + txt_again.nextLine(); if you want all the contents in one string.
}
Or you can assign it to a string txt_name and print that out.
http://www.functionx.com/java/Lesson23.htm
For adding arguments, add a String[] args as one of the parameters in your main function.
public static void main(String[] args)
And access the arguments as args[0], args[1] etc
Google Guava has utility methods for reading an entire file into a String, also for reading a file into a list of lines, etc.
For example,
import java.io.File;
import java.io.IOException;
import java.util.Scanner;
import com.google.common.base.Charsets;
import com.google.common.io.Files;
class Scratch {
public static void main(String[] args) throws IOException {
final String filename = args[0];
final File txt = new File(filename);
System.out.println("Here's your file: " + filename);
System.out.println(Files.toString(txt, Charsets.UTF_8));
System.out.print("Type the filename again: ");
final String fileAgain = new Scanner(System.in).nextLine();
final File txt_again = new File(fileAgain);
System.out.println(Files.toString(txt_again, Charsets.UTF_8));
}
}

LinkedList from .txt file (how to read everything but the first value of each line)

My ultimate goal is to create a linked list that compares the number of friends a person has (i.e. in the list below Joe has 4 friends while Kay has 3 (Joe is the most popular). The data for the list is imported from a text file. My question now is how can I read everything but the first string value from the text file?
Right now the text file has the following string data:
Joe Sue Meg Ry Luke
Kay Trey Phil George
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.List;
import java.util.*;
public class Main {
public static void main(String[] args) {
List<String[]> list1 = new LinkedList<String[]>();
// Read the file
try {
BufferedReader in = new BufferedReader(new FileReader("C:\\friendsFile"));
String names;
// Keep reading while there is still more data
while ((names = in.readLine()) != null) {
// Line by line read & add to array
String arr[] = names.split(" ");
String first = arr[0];
System.out.print("\nFirst name: " + first);
if (arr.length > 0)
list1.add(arr);
}
in.close();
// Catch exceptions
} catch (FileNotFoundException e) {
System.out.println("We're sorry, we are unable to find that file: \n" + e.getMessage());
} catch (IOException e) {
System.out.println("We're sorry, we are unable to read that file: \n" + e.getMessage());
}
}
}
In order to save an array that contains all names except the first, separately for each line in your file, you could replace
list1.add(arr);
by the following:
list1.add(Arrays.copyOfRange(arr, 1, arr.length));
Just a quick note here a file of names where first name last name and middle name are separated by space will be impossible for you to sort. One cannot assume that every name is compose of only first and last name. Maybe I got it wrong by reading your question but you will need more like a CSV file where every name would be separated by a comma then you could use something like:
String[] array = String.split(",");
int numberOfFriend = array.length - 1;
Consider using Guava:
Iterable<String> elements = Splitter.on(" ").split(line);
String firstNameInLine = Iterables.getFirst(elements);
Iterable<String> restOfNamesInLine = Iterables.skip(elements, 1);
Iterables
Splitter
What you could do, is to call the readLine() one time just before entering your while-loop, and not adding it to the array.

Categories