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);
Related
The assignment is to read a file, create a new file that matches the input file but has numbers lines added
I have several examples to copy from. I have tried new File(), new FileReader() and BufferedReader(). I can't seem to get any data out of the input file
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.PrintWriter;
import java.util.Scanner;
import java.util.ArrayList;
public class Hw1_43 {
public static void main(String[] args) throws FileNotFoundException
{
// Prompt user for input file name
Scanner in = new Scanner(System.in);
System.out.print("Enter input file name: ");
String inputFileName = in.next(); // instantiate input file name for later use
Scanner inputFile = new Scanner(new FileReader(inputFileName));
//ArrayList<String> line = new ArrayList();
int counter = 0;
while (inputFile.hasNextLine()) {
String line = inputFile.nextLine();
System.out.println(counter + line);
counter ++;
}
System.out.println(inputFileName);
}
}
Also after I get the input file to read and write it into an output file, where is the output file so I can look at it to make sure it is correct?
FileReader only reads from a file. You need to create a FileWriter, which writes to a file (e.g. FileWriter outputFile = new FileWriter ("C:/tmp/output_file.txt")). As you read from the FileWriter, prepend the line numbers to each line, then write to the FileWriter.
I recommend using BufferedReader instead of Scanner. You can then use then uses the .readLine() or .lines() methods, the latter can be streamed into a BufferedWriter.
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.
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".
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
I'm trying to make it so whenever a user inputs a name and pass it will write that information(in the format of name,pass) to a .csv file specified by the location. However whenever I run the program, it keeps overwriting the first line. I tried adding "\n" and out.newLine(); but for some reason it doesn't write to the next line. I have no idea why it does this so I was hoping if someone knows why.
public class TestClass {
public static void main(String[] args) throws IOException {
String location = "my location to the file (.csv)";
Scanner sc = new Scanner(System.in);
System.out.print("Name: ");
String name = sc.next();
System.out.print("Pass: ");
String pass = sc.next();
BufferedWriter out = new BufferedWriter(new FileWriter(location));
out.write(name + "," + pass + "\n");
out.newLine();
out.close();
}
}
Currently in the file I have this:
test, one
and when I ran the program:
name: one
pass: two
exited the program and checked the file and the first line was replaced with one,two instead of making it like this:
test, one
one, two
Thank you for those who help :)
Use the second constructor of FileWriter:
FileWriter(String fileName, boolean append)
fileName - String The system-dependent filename.
append - boolean if true, then data will be written to the end of the file rather than the beginning.
BufferedWriter out = new BufferedWriter(new FileWriter(location, true));