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
Related
I can read file using java.io and java.util.Scanner but I don't know how to read file using only java.util.Scanner:
import java.io.*;
import java.util.Scanner;
public class Main {
public static void main(String[] args) throws IOException {
String filePath = "C:\\IdeaProjects\\test\\src\\input.txt";
Scanner sc = new Scanner(new File(filePath));
int a, b;
a = sc.nestInt();
b = sc.nextInt();
}
}
Can someone help?
Since Scanner requires a java.io.File object, I don't think there's a way to read with Scanner only without using any java.io classes.
Here are two ways to read a file with the Scanner class - using default encoding and an explicit encoding. This is part of a long guide of how to read files in Java.
Scanner – Default Encoding
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class ReadFile_Scanner_NextLine {
public static void main(String [] pArgs) throws FileNotFoundException {
String fileName = "c:\\temp\\sample-10KB.txt";
File file = new File(fileName);
try (Scanner scanner = new Scanner(file)) {
String line;
boolean hasNextLine = false;
while(hasNextLine = scanner.hasNextLine()) {
line = scanner.nextLine();
System.out.println(line);
}
}
}
}
Scanner – Explicit Encoding
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class ReadFile_Scanner_NextLine_Encoding {
public static void main(String [] pArgs) throws FileNotFoundException {
String fileName = "c:\\temp\\sample-10KB.txt";
File file = new File(fileName);
//use UTF-8 encoding
try (Scanner scanner = new Scanner(file, "UTF-8")) {
String line;
boolean hasNextLine = false;
while(hasNextLine = scanner.hasNextLine()) {
line = scanner.nextLine();
System.out.println(line);
}
}
}
}
if you want to read the file until the end:
String filePath = "C:\\IdeaProjects\\test\\src\\input.txt";
File file = new File(filePath);
try {
Scanner sc = new Scanner(file);
while (sc.hasNextLine()) {
int i = sc.nextInt();
System.out.println(i);
}
sc.close();
}
catch (FileNotFoundException e) {
e.printStackTrace();
}
p.s If every line have only Integer I suggest you to use
Integer.parseInt(sc.readLine());
instead of sc.nextInt();
If you cant read please send me file Context
Well, if you are using a Mac, you type this into the terminal file.java<input.txt and to output to a file you type this: file.java>output.txt output.txt is a non-existing file, while input.txt is a pre-existing file.
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);
}
}
}
I want to be able to remove blank lines from a text file, for example:
Average Monthly Disposable Salary
1
Switzerland
$6,301.73
2014
2
Luxembourg
$4,479.80
2014
3
Zambia
$4,330.98
2014
--To This:
Average Monthly Disposable Salary
1
Switzerland
$6,301.73
2014
2
Luxembourg
$4,479.80
2014
3
Zambia
$4,330.98
2014
All of the code I have is below:
public class Driver {
public static void main(String[] args)
throws Exception {
Scanner file = new Scanner(new File("src/data.txt"));
PrintWriter write = new PrintWriter("src/data.txt");
while(file.hasNext()) {
if (file.next().equals("")) {
continue;
} else {
write.write(file.next());
}
}
print.close();
file.close();
}
}
The problem is that the text file is empty once I go back and look at the file again.
Im not sure why this is acting this way since they all seem to be blank characters, \n showing line breaks
Your code was almost correct, but there were a few bugs:
You must use .nextLine() instead of .next()
You must write to a different file while reading the original one
Your print.close(); should be write.close();
You forgot to add a new line after each line written
You don't need the continue; instruction, since it's redundant.
public static void main(String[] args) {
Scanner file;
PrintWriter writer;
try {
file = new Scanner(new File("src/data.txt"));
writer = new PrintWriter("src/data2.txt");
while (file.hasNext()) {
String line = file.nextLine();
if (!line.isEmpty()) {
writer.write(line);
writer.write("\n");
}
}
file.close();
writer.close();
} catch (FileNotFoundException ex) {
Logger.getLogger(Test.class.getName()).log(Level.SEVERE, null, ex);
}
}
If you want to keep the original name, you can do something like:
File file1 = new File("src/data.txt");
File file2 = new File("src/data2.txt");
file1.delete();
file2.renameTo(file1);
Try org.apache.commons.io and Iterator
try
{
String name = "src/data.txt";
List<String> lines = FileUtils.readLines(new File(name));
Iterator<String> i = lines.iterator();
while (i.hasNext())
{
String line = i.next();
if (line.trim().isEmpty())
i.remove();
}
FileUtils.writeLines(new File(name), lines);
}
catch (IOException e)
{
e.printStackTrace();
}
You could copy to a temporary file and rename it.
String name = "src/data.txt";
try(BufferedWriter bw = new BufferedWriter(name+".tmp)) {
Files.lines(Paths.get(name))
.filter(v -> !v.trim().isEmpty())
.forEach(bw::println);
}
new File(name+".tmp").renameTo(new File(name));
This piece of code solved this problem for me
package linedeleter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Scanner;
public class LineDeleter {
public static void main(String[] args) throws FileNotFoundException, IOException {
File oldFile = new File("src/data.txt"); //Declares file variable for location of file
Scanner deleter = new Scanner(oldFile); //Delcares scanner to read file
String nonBlankData = ""; //Empty string to store nonblankdata
while (deleter.hasNextLine()) { //while there are still lines to be read
String currentLine = deleter.nextLine(); //Scanner gets the currentline, stories it as a string
if (!currentLine.isBlank()) { //If the line isn't blank
nonBlankData += currentLine + System.lineSeparator(); //adds it to nonblankdata
}
}
PrintWriter writer = new PrintWriter(new FileWriter("src/data.txt"));
//PrintWriter and FileWriter are declared,
//this part of the code is when the updated file is made,
//so it should always be at the end when the other parts of the
//program have finished reading the file
writer.print(nonBlankData); //print the nonBlankData to the file
writer.close(); //Close the writer
}
}
As mentioned in the comments, of the code block, your sample had the print writer declared after your scanner meaning that the program had already overwritten your current file of the same name. Therefore there was no code for your scanner to read and thus, the program gave you a blank file
the
System.lineSeparator()
Just adds an extra space, this doesn't stop the program from continuing to write on that space, however, so it's all good
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();
}
im studying for my programming final exam. I have to write a program which opens a file which is stored in the string fileName and look in the file for a String called personName and this should print the first string after personName then the program should terminate after printing it,
if the argument personName is not in the file then it should print "this name doen't exsit" then if an IOException occurs it should then print "there is an IO Error" and the program should exsit using system.exit(0)
the program should use the file info.txt and each line should contain two strings
first string name and second age.
everything must be in one method
data.txt contains
Max 60.0
joe 19.0
ali 20.0
my code for this so far is :
public class Files{
public void InfoReader(String fileName, String personName)
{
try{
try{
// Open the file that is the first
// command line parameter
FileInputStream fstream = new FileInputStream("C://rest//data.txt");
// Get the object of DataInputStream
DataInputStream in = new DataInputStream(fstream);
BufferedReader br = new BufferedReader(new InputStreamReader(in));
//Read File Line By Line
while ((fileName = br.readLine()) != null) {
// Print the content on the console
(new Files()).infoReader("info.txt","Joe"); //this prints the age
}
//Close the input stream
in.close();
}
catch (IOException e)
{//Catch exception if any
System.out.println(" there is an IO Error");
System.exit(0);
}
}
catch (Exception e)
{//Catch exception if any
System.out.println("that name doesn't exists");
}
}
}
infoReader(info.txt,Joe); should print 19.0
But I am getting a java.lang.StackOverflowError
any help would be much appreciated!!
Thanks in advance!
This is what I think you are trying to do. And if doesn't, at least can work as an example. Just as amit mentions, your current error is because of the recursive call, which I think is not necessary.
import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
public class Files {
public void InfoReader(String fileName, String personName) {
try {
// Open the file that is the first command line parameter
FileInputStream fstream = new FileInputStream(fileName);
// Get the object of DataInputStream
DataInputStream in = new DataInputStream(fstream);
BufferedReader br = new BufferedReader(new InputStreamReader(in));
String line = null;
//Loop until there are no more lines in the file
while((line = br.readLine()) != null) {
//Split the line to get 'personaName' and 'age'.
String[] lineParts = line.split(" ");
//Compare this line personName with the one provided
if(lineParts[0].equals(personName)) {
//Print age
System.out.println(lineParts[1]);
br.close();
System.exit(0);
}
}
br.close();
//If we got here, it means that personName was not found in the file.
System.out.println("that name doesn't exists");
} catch (IOException e) {
System.out.println(" there is an IO Error");
}
}
}
If you use the Scanner class, it would make your life so much easier.
Scanner fileScanner = new Scanner (new File(fileName));
while(fileScanner.hasNextLine()
{
String line = fileScanner.nextLine();
Scanner lineScanner = new Scanner(line);
String name = lineScanner.next(); // gets the name
double age = Double.parseDouble(lineScanner.next()); // gets the age
// That's all really! Now do the rest!
}
Use commons-io and dont forget the encoding!
List<String> lines = FileUtils.readLines(file, encoding)