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);
}
}
}
Related
This is the prompt I was given
"Write a program and use the attached file (babynames.txt) as input file, and create two output tiles. One file listing out all boys names, and the other file listing out all girls name"
Here is what I have so far
import java.io.File;
import java.io.FileNotFoundException;
import java.io.PrintWriter;
import java.util.Scanner;
public class BabyNames
{
public static void main(String[] args) throws FileNotFoundException
{
// Prompt for the input and output file names
Scanner console = new Scanner(System.in);
System.out.println("Input file: ");
String inputFileName = console.next();
System.out.println("Output file 1: ");
String outputBoysNames = console.next();
System.out.println("Output file 2: ");
String outputGirlsNames = console.next();
// Construct the Scanner and PrintWriter objects for reading and writing
File inputFile = new File(inputFileName); // creates variable that reads from txt
Scanner in = new Scanner(inputFile);
PrintWriter out = new PrintWriter(outputBoysNames); // writes to output file (variable name)
PrintWriter out2 = new PrintWriter(outputGirlsNames);
// Read the input and write the output
while (in.hasNextLine()) {
String A = in.next();
String B = in.next();
String C = in.next();
String D = in.next();
String E = in.next();
String F = in.next();
String G = in.next();
out.printf(B);
out2.print(E);
}
in.close(); // Prevents this file is being used error
out.close();
out2.close();
}
}
I would assume that I would need to input the data from the text file into an array. Each token is separated by a space. I don't know how to approach this. Also, after the array is set up would I need to change the out.printf() and out2.printf() to an if loop to put the tokens I want into their respective txt file.
Example line from input txt file
1 Michael 462085 2.2506 Jessica 302962 1.5436
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)
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();
}
}
I'm having some problems reading some numbers separated by ":" from a txt file in java.
This is what i have so far:
public static void main(String []args) {
Scanner keyb = new Scanner(System.in);
System.out.print("Enter input file name: ");
String inputFile = keyb.nextLine();
System.out.print("Enter output file name: ");
String outputFile = keyb.nextLine();
File file = new File(inputFile);
try {
Scanner sc = new Scanner (file);
while (sc.hasNextLine()) {
System.out.println(sc.nextLine());
}
} catch(FileNotFoundException e) {
System.out.println("File not found!");
}
}
File numbers.txt
12.1:15.42
0.23:0.25
-9.2:-8.1
13.5:15.9
1024:1023.9
1.0e-3:1.0e-4
15.92:-9.35
18.26:6.4
55.931:55.930
256:512
I dont understand why its not being read...any help would be much appreciated! thank you!
I tried testing your program and got correct output. Take a look
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class Read {
public static void main(String[] args) {
File file = new File("numbers.txt");
try {
#SuppressWarnings("resource")
Scanner sc = new Scanner(file);
while (sc.hasNextLine()) {
System.out.println(sc.nextLine());
}
} catch (FileNotFoundException e) {
System.out.println("File not found!");
}
}
}
Output:
12.1:15.42
0.23:0.25
-9.2:-8.1
13.5:15.9
1024:1023.9
1.0e-3:1.0e-4
15.92:-9.35
18.26:6.4
55.931:55.930
256:512
I recommend using java.util.BufferedReader to read a file. There generally easy to use compared to the Scanner class.
...
BufferedReader br = new BufferedReader(new FileReader(inputFile));
String inLine; //Buffer used to store the current line
while ((inLine = br.readLine()) != null) //keep reading until we reach the end of file
{
System.out.println(inLine);
}
Tutorial: Java >> BufferedReader
Make use of the split method in the string class and equate the output to an array,each index will have a different number if they are all indeed seperated by the same character that you have specified above: http://docs.oracle.com/javase/7/docs/api/java/lang/String.html and http://www.coderanch.com/t/385246/java/java/split-method-String-API might help but I strongly recon u download all the APIs
Intro java class tard here. I'm trying to read data from a file and then manipulate to a different file and save it. I think i'm close but having issues using scanner and .IO together. Any help would be great.
import java.util.Scanner;
import java.io.*;
public class fileswitch
{
public static void main(String[] Args) throws IOException
{
String filename;
String filename2;
String text;
Scanner keyboard = new Scanner(System.in);
System.out.print("Enter the name of a file: ");
filename = keyboard.nextLine();
PrintWriter outputFile = new PrintWriter(filename);
System.out.print("Enter the name of a second file: ");
filename2 = keyboard.nextLine();
PrintWriter outputFile2 = new PrintWriter(filename2);
while (filename.hasNextLine())
{
text = filename.readAllLines();
text = text.toUpperCase();
outputFile2.print(text);
outputFile2.close();
}
}
}
You can also use for creating a new file
package test;
import java.io.File;
import java.io.IOException;
import org.apache.commons.io.FileUtils;
public class WriteStringToFile {
public static void main(String[] args) throws IOException {
String string = "This is\na test";
File file = new File("test.txt");
FileUtils.writeStringToFile(file, string);
}
}
And that is a good practice because you do not have to close streams.
This generates the test.txt file with the expected output
Try using BufferedReader
BufferedReader pw = new BufferedReader(new FileReader(fileName));
String s = null;
s = pw.readLine();
Working example
public static void main(String[] args) throws IOException {
Scanner keyboard = new Scanner(System.in);
String filePath = keyboard.next();
BufferedReader bufferedReader = new BufferedReader(new FileReader(filePath));
String line = bufferedReader.readLine();
System.out.println(line);
}
Enter path on console as
C:\Users\path\Desktop\1.txt
You can use PrintWriter to write
PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter(fileName2)));
Your code does not compile.
while (filename.hasNextLine()) // String#hasNextLine() does not exist
hasNextLine() belongs to Scanner which isn't being used for reading the file but just your console keystrokes from the keyboard.
If you meant to use outputFile there; that won't work either because you can't use a PrintWriter as a file reader. Well, the name kind of makes that obvious. Doesn't it?
But, you should avoid using PrintWriter for writing as well unless you're formatting the output. For plain character output prefer a FileWriter (enclosed within a BufferedWriter for performance). Similarly, for reading the files prefer a FileReader (enclosed within a BufferedReader again).
Here's how your code would look:
public static void main(String[] Args) throws IOException
{
// create the scanner for console
Scanner keyboard = new Scanner(System.in);
// read the input/output file names
System.out.print("Enter the name of a file: ");
String inFile = keyboard.nextLine();
System.out.print("Enter the name of a second file: ");
String outFile = keyboard.nextLine();
// close the scanner
keyboard.close();
// open file streams
BufferedReader reader = new BufferedReader(new FileReader(inFile));
BufferedWriter writer = new BufferedWriter(new FileWriter(outFile));
// copy the data (line by line)
String text = null;
while ((text = reader.readLine()) != null)
{
writer.write(text);
writer.newLine();
}
// close the file streams
reader.close();
writer.close();
}