Inputting a file into Java to make a new output file - java

I am working on a project where we have to create an input file with a poem or a song, and with that file we are supposed to create a program that creates an output file with the input file updated with line numbers. Here is an example: If the input file is: Mary had a little lamb, the output file should look like: /* 1 */ Mary had a little lamb. The code should do this for each line, incrementing the numbers for each line. Below is the code that I have so far, but I am unsure what to do next.
package morrisJCh7Sec2;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.PrintWriter;
import java.util.Scanner;
public class PoemTextFile {
public static void main(String args[]) throws FileNotFoundException {
File inputFile = new File("poem.txt");
Scanner input = new Scanner(inputFile);
PrintWriter outputFile = new PrintWriter("numpoem.txt");
outputFile.printf("Read in %s. \nWrote out %s.", inputFile, outputFile);
input.close();
outputFile.close();
}
}
This is what my assignment is. I have already created the text file, but when I ran my code the way it is right now, it said that it could not find my file that I had created.
Create a text file with a poem or song lyrics. (If you can’t think of
a poem or song, use Mary had a little lamb.) Put one line of the poem
or song on one line of the text file. Pay attention to your spelling
and punctuation. Use this file as your input file. Write code to read
each line from your input file. Write each line to an output file with
the line number preceeding the line. Be sure to follow this example
for the format of the line number.
Here is the error I receive:
Exception in thread "main" java.io.FileNotFoundException: poem.txt
(The system cannot find the file specified) at
java.io.FileInputStream.open0(Native Method) at
java.io.FileInputStream.open(Unknown Source) at
java.io.FileInputStream.(Unknown Source) at
java.util.Scanner.(Unknown Source) at
morrisJCh7Sec2.PoemTextFile.main(PoemTextFile.java:11)

You are close.
Just iterate over the lines of the text:
File inputFile = new File("poem.txt");
Scanner input = new Scanner(inputFile);
input.useDelimiter("\n");
PrintWriter outputFile = new PrintWriter("numpoem.txt");
int count = 0;
while(input.hasNext()) {
outputFile.print("/* " + count++ + " */ " + input.next() + "\n");
}
input.close();
outputFile.close();
The delimiter \n (newline) ensures that every new chunk of data read by the Scanner is a line from the text file. The while loop runs until there are no more lines to read. Then you write the line to the target file, adding the line number by using a counting variable which is incremented by the ++ for every line. If you want to start counting at 1, just change the initial value of count.

Related

Append text to the beginning of every line in a file

Please note, this is a homework assignment.
Can anybody help me figure out how to append text to the beginning of every line of a text file? This is what I have so far:
package addStr;
import java.util.*;
import java.io.*;
public class AddStr {
public static void main(String args[]) throws FileNotFoundException, IOException{
Scanner con = new Scanner(System.in);
System.out.print("Enter input file: ");
String fileIn = con.next();
System.out.print("Enter output file: ");
String fileOut = con.next();
File in = new File(fileIn);
Scanner sc = new Scanner(in);
FileWriter out = new FileWriter(in, true);
PrintWriter print = new PrintWriter(out);
print.print("hello");
print.close();
}
}
I only printed "hello" as a test to see where in the file it would append. It appends at the end of the very last line. I need it to append to the beginning of the first line, and then use a loop to append it to the beginning of each subsequent line.
Also, the program prompts the user to input the file name.
The simplest way to change the content of a file is to open it for reading, read it into a structure, re-open the file for writing then write from the structure back to file. Unless the file is large then the performance will be perfectly acceptable.
If you are using Java 8 then this can be quite trivial. Assuming you have a Path to the file:
List<String> lines = Files.lines(path).map(s -> "Prefix" + s).collect(Collectors.toList());
Files.write(path, lines);

Another java.io.FileNotFoundException (The system cannot find the file specified) thread

I've created a basic notepad text file (e.g., text-file.txt) and have tried placing this file in multiple file paths for my code to retrieve, but I can't seem to get this to work. Basically, I'm wanting to take the content of text-file.txt and create a second file where everything is in all caps.
Here is my code:
package abc123;
import java.util.Scanner;
import java.io.FileReader;
import java.io.IOException;
import java.io.PrintWriter;
public class abc123
{
public static void main (String [] args) throws IOException
{
Scanner in = new Scanner(System.in);
System.out.print("Please provide the name of your input file: ");
String inFileName = in.nextLine();
System.out.print("Please indicate what you'd like to name your output file: ");
String outFileName = in.nextLine();
FileReader reader = new FileReader(inFileName);
PrintWriter writer = new PrintWriter(outFileName);
Scanner fileReader = new Scanner(reader);
while(fileReader.hasNext())
{
String line = fileReader.nextLine();
line = line.toUpperCase();
writer.println(line);
}
fileReader.close();
writer.close();
System.out.println("The process is now complete. Please check your output file. Thank you.");
}
}
I'm a Java newbie, so a simple solution (and comments, as always) that I can grasp at this point would be super helpful. Thanks!
if the file isn't in the same folder as your java class, you have to give java full-path to find the file. be sure you also type the extension of the file, like ".txt".

How do I make a file's contents scanned and printed?

Using java, I need to make a program that asks the user which file to scan, and to do some work with the data in the file.
My program is supposed to select a file, scan the file for a specific character that the user specifies, and return with how many specific characters there are in that file.
This is my code so far:
import java.io.*;
import java.util.Scanner;
public class CharSearch {
public static void main(String[] args) throws Exception{
Scanner scanner = new Scanner(System.in);
System.out.println("Enter the name of the file you want to search.");
String fileInput = scanner.nextLine();
System.out.println("What character would you like to look for in " + fileInput + "?");
Scanner fileScanner = new Scanner(fileInput);
System.out.println(fileScanner);
}
}
I imported io and scanner, then set up the scanner to read which file the user inputs. I print back out that file name. The last two lines are where I need help. How can I make the scanner return with the data in the file.
There is a file in my folder called data.txt and all that is written in it is "dataWord." For starters, I want the scanner to read the file and the program to display dataWord, but its not working. I am a rookie, so please work with me. Thanks.
Instead of passing path of file as String pass it as a File
Scanner fileScanner = new Scanner(new File(fileInput));
while (fileScanner.hasNext()) {
System.out.println(fileScanner.next());
}
scanner.close();
fileScanner.close();
If the file is an external file or not in your project, you can specify the absolute path of file.
If it is in classpath you can read using ClassLoader
java.io.InputStream inputStream = this.getClassLoader().getResourceAsStream("file_path")
Scanner has a constructor with InputStream

Java scanner not starting from beginning of file

First of all this is not a duplicate of other posts, because in my problem the scanner class does not recognize the beginning of the .txt file not the end, instead it starts approximately 1/2 way through the file.
Here is my code:
package Program;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class App {
public static void main(String[] args) throws FileNotFoundException {
String filename = "C:\\Users\\vroy\\Programming\\Text documents\\P&P.txt";
File textFile = new File(filename);
Scanner reader = new Scanner(textFile);
// int value = reader.nextInt();
// System.out.println(value);
while (reader.hasNextLine()) {
String line = reader.nextLine();
System.out.println(line);
}
reader.close();
}
}
Here is the .txt document that my program is reading:
http://www.goodreads.com/ebooks/download/1885.Pride_and_Prejudice?doc=2
My program starts printing out lines of text starting at: "with the ill-judged officiousness..."
It should start much further up the document.
Is this a problem with the scanner class?
Is this a problem with the scanner class?
Nope.
I just tested your code. The answer is pretty funny actually - I assume you are running this code in an IDE such as Eclipse. System.out.println() prints to the "Console". The console has a maximum number of lines it shows, and as your file is very long, it doesn't show the start.
It IS looping through all the lines. To prove this, make it increment a digit whenever it prints a line such as:
int counter = 0;
while (reader.hasNextLine()) {
String line = reader.nextLine();
System.out.println(line);
counter++;
}
You will see that counter is exactly the number of lines in the document.

for loop not iterating through all increments

I'm writing a program for a lab task at uni, the code will make is fairly obvious what is does, but when it asks for the first line, ie number one 1 in the loop, and you insert a string and hit enter, it automatically jumps straight to the last increment in the loop (5) any ideas?
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.PrintWriter;
import java.util.Scanner;
public class limmerickWriter {
public static void main(String[] args)throws Exception {
Scanner limScan = new Scanner(System.in); //scanner to read user input
System.out.println("please enter the name of the file");
String fileName;
fileName = limScan.next(); //filename for the text file
PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter(fileName))); //declaring a new file writer
for (int i = 1; i <= 5; i++) //loop to get 5 seperate lines from the user
{
System.out.println("please enter line " + i );
out.println(limScan.next()); //writes the contents of the scanner to the file
}
out.flush();
out.close();
}
}
While reading with scanner.next() white space gets used as default delimiter. Which means that if your file name is inserted with several words separated by spaces,they will be read with continuous next() call first.
For example, while reading the filename using scanner.next(), if you insert:
test ATest BTest CTest DTest ETest
And hit Enter, you will see that a file with name test gets created in your relevant class path, containing text data ATest BTest CTest DTest ETest.
Try using nextLine() instead inside the for loop.

Categories

Resources