Reading files in Java vs. Python - java

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));
}
}

Related

File manipulation (changing lines in a File) in java

I'm trying to read in a file and change some lines.
The instruction reads "invoking java Exercise12_11 John filename removes the string John from the specified file."
Here is the code I've written so far
import java.util.Scanner;
import java.io.*;
public class Exercise12_11 {
public static void main(String[] args) throws Exception{
System.out.println("Enter a String and the file name.");
if(args.length != 2) {
System.out.println("Input invalid. Example: John filename");
System.exit(1);
}
//check if file exists, if it doesn't exit program
File file = new File(args[1]);
if(!file.exists()) {
System.out.println("The file " + args[1] + " does not exist");
System.exit(2);
}
/*okay so, I need to remove all instances of the string from the file.
* replacing with "" would technically remove the string
*/
try (//read in the file
Scanner in = new Scanner(file);) {
while(in.hasNext()) {
String newLine = in.nextLine();
newLine = newLine.replaceAll(args[0], "");
}
}
}
}
I don't quite know if I'm headed in the correct direction because I'm having some issue getting the command line to work with me. I only want to know if this is heading in the correct direction.
Is this actually changing the lines in the current file, or will I need different file to make alterations? Can I just wrap this in a PrintWriter to output?
Edit: Took out some unnecessary information to focus the question. Someone commented that the file wouldn't be getting edited. Does that mean I need to use PrintWriter. Can I just create a file to do so? Meaning I don't take a file from user?
Your code is only reading file and save lines into memory. You will need to store all modified contents and then re-write it back to the file.
Also, if you need to keep newline character \n to maintain format when re-write back to the file, make sure to include it.
There are many ways to solve this, and this is one of them. It's not perfect, but it works for your problem. You can get some ideas or directions out of it.
List<String> lines = new ArrayList<>();
try {
Scanner in = new Scanner(file);
while(in.hasNext()) {
String newLine = in.nextLine();
lines.add(newLine.replaceAll(args[0], "") + "\n"); // <-- save new-line character
}
in.close();
// save all new lines to input file
FileWriter fileWriter = new FileWriter(args[1]);
PrintWriter printWriter = new PrintWriter(fileWriter);
lines.forEach(printWriter::print);
printWriter.close();
} catch (IOException ioEx) {
System.err.println("Error: " + ioEx.getMessage());
}

Trying to Make a Vigenere Encrypter in Java [duplicate]

I am working on a Java program that reads a text file line-by-line, each with a number, takes each number throws it into an array, then tries and use insertion sort to sort the array. I need help with getting the program to read the text file.
I am getting the following error messages:
java.io.FileNotFoundException: 10_Random (The system cannot find the file specified)
at java.io.FileInputStream.open(Native Method)
at java.io.FileInputStream.<init>(Unknown Source)
at java.util.Scanner.<init>(Unknown Source)
at insertionSort.main(insertionSort.java:14)
I have a copy of the .txt file in my "src" "bin" and main project folder but it still cannot find the file. I am using Eclipse by the way.
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class insertionSort {
public static void main(String[] args) {
File file = new File("10_Random");
try {
Scanner sc = new Scanner(file);
while (sc.hasNextLine()) {
int i = sc.nextInt();
System.out.println(i);
}
sc.close();
}
catch (FileNotFoundException e) {
e.printStackTrace();
}
}
}
You have to put file extension here
File file = new File("10_Random.txt");
Use following codes to read the file
import java.io.File;
import java.util.Scanner;
public class ReadFile {
public static void main(String[] args) {
try {
System.out.print("Enter the file name with extension : ");
Scanner input = new Scanner(System.in);
File file = new File(input.nextLine());
input = new Scanner(file);
while (input.hasNextLine()) {
String line = input.nextLine();
System.out.println(line);
}
input.close();
} catch (Exception ex) {
ex.printStackTrace();
}
}
}
-> This application is printing the file content line by line
here are some working and tested methods;
using Scanner
package io;
import java.io.File;
import java.util.Scanner;
public class ReadFromFileUsingScanner {
public static void main(String[] args) throws Exception {
File file=new File("C:\\Users\\pankaj\\Desktop\\test.java");
Scanner sc=new Scanner(file);
while(sc.hasNextLine()){
System.out.println(sc.nextLine());
}
}
}
Here's another way to read entire file (without loop) using Scanner class
package io;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class ReadingEntireFileWithoutLoop {
public static void main(String[] args) throws FileNotFoundException {
File file=new File("C:\\Users\\pankaj\\Desktop\\test.java");
Scanner sc=new Scanner(file);
sc.useDelimiter("\\Z");
System.out.println(sc.next());
}
}
using BufferedReader
package io;
import java.io.*;
public class ReadFromFile2 {
public static void main(String[] args)throws Exception {
File file=new File("C:\\Users\\pankaj\\Desktop\\test.java");
BufferedReader br=new BufferedReader(new FileReader(file));
String st;
while((st=br.readLine())!=null){
System.out.println(st);
}
}
}
using FileReader
package io;
import java.io.*;
public class ReadingFromFile {
public static void main(String[] args) throws Exception {
FileReader fr=new FileReader("C:\\Users\\pankaj\\Desktop\\test.java");
int i;
while((i=fr.read())!=-1){
System.out.print((char) i);
}
}
}
Make sure the filename is correct (proper capitalisation, matching extension etc - as already suggested).
Use the Class.getResource method to locate your file in the classpath - don't rely on the current directory:
URL url = insertionSort.class.getResource("10_Random");
File file = new File(url.toURI());
Specify the absolute file path via command-line arguments:
File file = new File(args[0]);
In Eclipse:
Choose "Run configurations"
Go to the "Arguments" tab
Put your "c:/my/file/is/here/10_Random.txt.or.whatever" into the "Program arguments" section
No one seems to have addressed the fact that your not entering anything into an array at all. You are setting each int that is read to "i" and then outputting it.
for (int i =0 ; sc.HasNextLine();i++)
{
array[i] = sc.NextInt();
}
Something to this effect will keep setting values of the array to the next integer read.
Than another for loop can display the numbers in the array.
for (int x=0;x< array.length ; x++)
{
System.out.println("array[x]");
}
You need the specify the exact filename, including the file extension, e.g. 10_Random.txt.
The file needs to be in the same directory as the executable if you want to refer to it without any kind of explicit path.
While we're at it, you need to check for an int before reading an int. It is not safe to check with hasNextLine() and then expect an int with nextInt(). You should use hasNextInt() to check that there actually is an int to grab. How strictly you choose to enforce the one integer per line rule is up to you, of course.
private void loadData() {
Scanner scanner = null;
try {
scanner = new Scanner(new File(getFileName()));
while (scanner.hasNextLine()) {
Scanner lijnScanner = new Scanner(scanner.nextLine());
lijnScanner.useDelimiter(";");
String stadVan = lijnScanner.next();
String stadNaar = lijnScanner.next();
double km = Double.parseDouble(lijnScanner.next());
this.voegToe(new TweeSteden(stadVan, stadNaar), km);
}
} catch (FileNotFoundException e) {
throw new DbException(e.getMessage(), e);
} finally {
if(scanner != null){
scanner.close();
}
}
}
File Path Seems to be an issue here please make sure that file exists in the correct directory or give the absolute path to make sure that you are pointing to a correct file.
Please log the file.getAbsolutePath() to verify that file is correct.
You should use either
File file = new File("bin/10_Random.txt");
Or
File file = new File("src/10_Random.txt");
Relative to the project folder in Eclipse.
The file you read in must have exactly the file name you specify: "10_random" not "10_random.txt" not "10_random.blah", it must exactly match what you are asking for. You can change either one to match so that they line up, but just be sure they do. It may help to show the file extensions in whatever OS you're using.
Also, for file location, it must be located in the working directory (same level) as the final executable (the .class file) that is the result of compilation.
At first check the file address, it must be beside your .java file or in any address that you define in classpath environment variable. When you check this then try below.
you must use a file name by it's extension in File object constructor, as an example:
File myFile = new File("test.txt");
but there is a better way to use it inside Scanner object by pass the filename absolute address, as an example:
Scanner sc = new Scanner(Paths.get("test.txt"));
in this way you must import java.nio.file.Paths as well.

having issues with Java reading input files using netbeans

Following is my code that I am working on for a school project. It does ok up until I try to read the animal.txt file. Can someone please tell me what I am doing wrong? I am attaching my compilation error as an image. Thanks in advance.
[input error image1
package finalproject;
//enabling java programs
import java.util.Scanner;
import javax.swing.JOptionPane;
import java.io.FileInputStream;
import java.io.IOException;
public class Monitoring {
public static void choseAnimal() throws IOException{
FileInputStream file = null;
Scanner inputFile = null;
System.out.println("Here is your list of animals");
file = new FileInputStream("\\src\\finalproject\\animals.txt");
inputFile = new Scanner(file);
while(inputFile.hasNext())
{
String line = inputFile.nextLine();
System.out.println(line);
}
}
public static void choseHabit(){
System.out.println("Here is your list of habits");
}
public static void main(String[] args) throws IOException{
String mainOption = ""; //user import for choosing animal, habit or exit
String exitSwitch = "n"; // variable to allow exit of system
Scanner scnr = new Scanner(System.in); // setup to allow user imput
System.out.println("Welcome to the Zoo");
System.out.println("What would you like to monitor?");
System.out.println("An animal, habit or exit the system?");
mainOption = scnr.next();
System.out.println("you chose " + mainOption);
if (mainOption.equals("exit")){
exitSwitch = "y";
System.out.println(exitSwitch);
}
if (exitSwitch.equals( "n")){
System.out.println("Great, let's get started");
}
if (mainOption.equals("animal")){
choseAnimal();
}
if (mainOption.equals("habit")) {
choseHabit();
}
else {
System.out.println("Good bye");
}
}
}
\\src\\finalproject\\animals.txt suggests that the file is an embedded resource.
First, you should never reference src in you code, it won't exist once the program is built and package.
Secondly, you need to use Class#getResource or Class#getResourceAsStream in order to read.
Something more like...
//file = new FileInputStream("\\src\\finalproject\\animals.txt");
//inputFile = new Scanner(file);
try (Scanner inputFile = new Scanner(Monitoring.class.getResourceAsStream("/finalproject/animals.txt"), StandardCharsets.UTF_8.name()) {
//...
} catch (IOException exp) {
exp.printStackTrace();
}
for example
Now, this assumes that file animals.txt exists in the finalproject package
The error message clearly shows that it can't find the file. This means there's two possibilities:
File does not exist in the directory you want
Directory you want is not the directory you have.
I would start by creating a File object looking at "." (current directory) to and printing that to see what directory it looks by default. You may need to hard code the file path, depending on what netbeans is using for a default directory.

File I/O Practice.

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()

Reading a .txt file using Scanner class in Java

I am working on a Java program that reads a text file line-by-line, each with a number, takes each number throws it into an array, then tries and use insertion sort to sort the array. I need help with getting the program to read the text file.
I am getting the following error messages:
java.io.FileNotFoundException: 10_Random (The system cannot find the file specified)
at java.io.FileInputStream.open(Native Method)
at java.io.FileInputStream.<init>(Unknown Source)
at java.util.Scanner.<init>(Unknown Source)
at insertionSort.main(insertionSort.java:14)
I have a copy of the .txt file in my "src" "bin" and main project folder but it still cannot find the file. I am using Eclipse by the way.
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class insertionSort {
public static void main(String[] args) {
File file = new File("10_Random");
try {
Scanner sc = new Scanner(file);
while (sc.hasNextLine()) {
int i = sc.nextInt();
System.out.println(i);
}
sc.close();
}
catch (FileNotFoundException e) {
e.printStackTrace();
}
}
}
You have to put file extension here
File file = new File("10_Random.txt");
Use following codes to read the file
import java.io.File;
import java.util.Scanner;
public class ReadFile {
public static void main(String[] args) {
try {
System.out.print("Enter the file name with extension : ");
Scanner input = new Scanner(System.in);
File file = new File(input.nextLine());
input = new Scanner(file);
while (input.hasNextLine()) {
String line = input.nextLine();
System.out.println(line);
}
input.close();
} catch (Exception ex) {
ex.printStackTrace();
}
}
}
-> This application is printing the file content line by line
here are some working and tested methods;
using Scanner
package io;
import java.io.File;
import java.util.Scanner;
public class ReadFromFileUsingScanner {
public static void main(String[] args) throws Exception {
File file=new File("C:\\Users\\pankaj\\Desktop\\test.java");
Scanner sc=new Scanner(file);
while(sc.hasNextLine()){
System.out.println(sc.nextLine());
}
}
}
Here's another way to read entire file (without loop) using Scanner class
package io;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class ReadingEntireFileWithoutLoop {
public static void main(String[] args) throws FileNotFoundException {
File file=new File("C:\\Users\\pankaj\\Desktop\\test.java");
Scanner sc=new Scanner(file);
sc.useDelimiter("\\Z");
System.out.println(sc.next());
}
}
using BufferedReader
package io;
import java.io.*;
public class ReadFromFile2 {
public static void main(String[] args)throws Exception {
File file=new File("C:\\Users\\pankaj\\Desktop\\test.java");
BufferedReader br=new BufferedReader(new FileReader(file));
String st;
while((st=br.readLine())!=null){
System.out.println(st);
}
}
}
using FileReader
package io;
import java.io.*;
public class ReadingFromFile {
public static void main(String[] args) throws Exception {
FileReader fr=new FileReader("C:\\Users\\pankaj\\Desktop\\test.java");
int i;
while((i=fr.read())!=-1){
System.out.print((char) i);
}
}
}
Make sure the filename is correct (proper capitalisation, matching extension etc - as already suggested).
Use the Class.getResource method to locate your file in the classpath - don't rely on the current directory:
URL url = insertionSort.class.getResource("10_Random");
File file = new File(url.toURI());
Specify the absolute file path via command-line arguments:
File file = new File(args[0]);
In Eclipse:
Choose "Run configurations"
Go to the "Arguments" tab
Put your "c:/my/file/is/here/10_Random.txt.or.whatever" into the "Program arguments" section
No one seems to have addressed the fact that your not entering anything into an array at all. You are setting each int that is read to "i" and then outputting it.
for (int i =0 ; sc.HasNextLine();i++)
{
array[i] = sc.NextInt();
}
Something to this effect will keep setting values of the array to the next integer read.
Than another for loop can display the numbers in the array.
for (int x=0;x< array.length ; x++)
{
System.out.println("array[x]");
}
You need the specify the exact filename, including the file extension, e.g. 10_Random.txt.
The file needs to be in the same directory as the executable if you want to refer to it without any kind of explicit path.
While we're at it, you need to check for an int before reading an int. It is not safe to check with hasNextLine() and then expect an int with nextInt(). You should use hasNextInt() to check that there actually is an int to grab. How strictly you choose to enforce the one integer per line rule is up to you, of course.
private void loadData() {
Scanner scanner = null;
try {
scanner = new Scanner(new File(getFileName()));
while (scanner.hasNextLine()) {
Scanner lijnScanner = new Scanner(scanner.nextLine());
lijnScanner.useDelimiter(";");
String stadVan = lijnScanner.next();
String stadNaar = lijnScanner.next();
double km = Double.parseDouble(lijnScanner.next());
this.voegToe(new TweeSteden(stadVan, stadNaar), km);
}
} catch (FileNotFoundException e) {
throw new DbException(e.getMessage(), e);
} finally {
if(scanner != null){
scanner.close();
}
}
}
File Path Seems to be an issue here please make sure that file exists in the correct directory or give the absolute path to make sure that you are pointing to a correct file.
Please log the file.getAbsolutePath() to verify that file is correct.
You should use either
File file = new File("bin/10_Random.txt");
Or
File file = new File("src/10_Random.txt");
Relative to the project folder in Eclipse.
The file you read in must have exactly the file name you specify: "10_random" not "10_random.txt" not "10_random.blah", it must exactly match what you are asking for. You can change either one to match so that they line up, but just be sure they do. It may help to show the file extensions in whatever OS you're using.
Also, for file location, it must be located in the working directory (same level) as the final executable (the .class file) that is the result of compilation.
At first check the file address, it must be beside your .java file or in any address that you define in classpath environment variable. When you check this then try below.
you must use a file name by it's extension in File object constructor, as an example:
File myFile = new File("test.txt");
but there is a better way to use it inside Scanner object by pass the filename absolute address, as an example:
Scanner sc = new Scanner(Paths.get("test.txt"));
in this way you must import java.nio.file.Paths as well.

Categories