Reading from a text file with a static constant declared - java

I'm trying to write a code that will read the contents of a file and I'm able to read it successfully. What I'm also trying to do is maybe declare a static constant like max_number_of_players so that the data read does not exceed this. Is there a way that I can do this? My code so far:
import java.io.*;
import java.util.*;
public class Test{
public static void main(String[] args) throws IOException
{
String fileName = "Data/players.txt";
File file = new File(fileName);
Scanner in = new Scanner(file);
while(in.hasNextLine()){
String line = in.nextLine();
System.out.println(line);
}
in.close();
}
}

Just add another condition to the while-loop:
int playerCount = 0;
while(in.hasNextLine() && playerCount++ < max_number_of_players){
...

Related

My java scanner doesn't seem to be reading my input (.txt file)

I am new to Java, and I am learning how to read input using Java on Eclipse. I am using a scanner to read a .txt input file, however, it doesn't seem to be reading the very first integer in the .txt file.
Here is the .txt file:
2 1 4
Here is my simplified code:
public class Test {
static int var;
static int[] arr;
public static void main(String[] args) {
String fileName = "/Users/anon/eclipse-workspace/Lab/src/input-01.txt";
readInput(fileName);
}
public static void readInput(String fileName) {
File file = new File(fileName);
Scanner fileInput = new Scanner(file);
//Read T
var = fileInput.nextInt();
System.out.printf("var: %d", var);
arr = new int[var];
}
I tried debugging, and I realized that "int var" never even appeared in the variables table on the right -- so I am not sure if "int var" was even initialized at all.
Please let me know if there are any other information that I can provide, and thank you in advance for you help and advices.
Check the input file contents. It could be a problem.
import java.io.File;
import java.util.Scanner;
public class Sample {
public static void main(String[] args) throws Exception {
String fileName = "src/main/resources/input-01.txt";
readInput(fileName);
}
public static void readInput(String fileName) throws Exception {
File file = new File(fileName);
Scanner fileInput = new Scanner(file);
//Read T
int var = fileInput.nextInt();
System.out.println("var = " + var);
}
}
input-01.txt file content
10 sampletext
output
var = 10
Process finished with exit code 0

Java read file using Scanner

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.

Write to files using Java

I am trying to use lists for my first time, I have a txt file that I am searching in it about string then I must write the result of searching in new file.
Check the image attached
My task is to retrieve the two checked lines of the input file to the output files.
And this is my code:
import java.io.*;
import java.util.Scanner;
public class TestingReport1 {
public static void main(String[] args) throws Exception {
File test = new File("E:\\test2.txt");
File Result = new File("E:\\Result.txt");
Scanner scanner = new Scanner(test);
while (scanner.hasNextLine()) {
String line = scanner.nextLine();
if(line.contains("Visit Count")|| line.contains("Title")) {
System.out.println(line);
}
}
}
}
What should I do?!
Edit: How can I write the result of this code into text file?
Edit2:
Now using the following code:
public static void main(String[] args) throws Exception {
// TODO code application logic here
File test = new File("E:\\test2.txt");
FileOutputStream Result = new FileOutputStream("E:\\Result.txt");
Scanner scanner = new Scanner(test);
while (scanner.hasNextLine()) {
String line = scanner.nextLine();
if(line.contains("Visit Count")|| line.contains("Title")) {
System.out.println(line);
Files.write(Paths.get("E:\\Result.txt"), line.getBytes(), StandardOpenOption.APPEND);
}
}
}
I got the result back as Visit Count:1 , and I want to get this number back as integer, Is it possible?
Have a look at Files, especially readAllLines as well as write. Filter the input between those two method calls, that's it:
// Read.
List<String> input = Files.readAllLines(Paths.get("E:\\test2.txt"));
// Filter.
String output = input.stream()
.filter(line -> line.matches("^(Title.*|Visit Count.*)"))
.collect(Collectors.joining("\n"));
// Write.
Files.write(Paths.get("E:\\Result.txt"), output.getBytes());

Java - Using multiple PrintWriter but saves only last println

I'm designing a program to split data stored in a text file into two separate files based on the label of that data.
Here is a small version of that data.
0,1,2,normal.
5,5,5,strange.
2,1,3,normal.
I use a class to store each line as a sample. The class parses the line to store the last value as the label. I encapsulated each line as an object, because I intend to add features later.
Here is code for the Sample class
import java.util.Scanner;
public class Sample {
String[]str_vals = new String[3];
String label;
Sample(Scanner line) {
for (int i=0; i<3; i++) {
str_vals[i] = line.next();
}
label = line.next();
}
String getValsForCSV() {
StringBuilder retval = new StringBuilder();
for (int i=0; i<3; i++) {
retval.append(str_vals[i]).append(",");
}
retval.append(label).append(".");
return retval+"";
}
String getLabel() {
return label;
}
}
Below is the code in question. My Separator class.
import java.io.*;
import java.util.Scanner;
public class Separator {
public static final String DATAFILE = "src/etc/test.txt";
public static void main(String[] args) throws FileNotFoundException {
runData();
}
public static void runData() throws FileNotFoundException {
try (Scanner in = new Scanner(new File(DATAFILE))) {
// kddcup file uses '.\n' at end of each line
// setting this as delimiter which will consume the period
in.useDelimiter("[.]\r\n|[.]\n|\n");
Sample curr;
while(in.hasNext()) {
// line will hold all fields for a single sample
Scanner line = new Scanner(in.next());
line.useDelimiter(", *");
curr = new Sample(line);
try (
PrintWriter positive = new PrintWriter(new File(DATAFILE+"-pos"));
PrintWriter negative = new PrintWriter(new File(DATAFILE+"-neg"));
) {
if (curr.getLabel().equals("normal")) {
positive.println("GOOD");
} else {
negative.println("BAD");
}
}
}
}
}
}
This issue that I am experiencing is that the code only saves the last Sample seen to its respective file. So with above data the test.txt-neg will be empty and test.txt-pos will have a single line GOOD; it does not have two GOOD's as expected.
If I modify the test.txt data to include only the first two lines, then the files states are reversed (i.e. test.txt-neg has BAD and test.txt-pos is empty). Could someone please explain to me what is going on, and how to fix this error?
Because the error was pointed out in a comment. I wanted to give credit to KevinO and Elliott Frisch for the solution.
As mentioned, I'm creating a new PrintWriter each time and creating the PrintWriter in it's default mode of overwriting a file. As a result it always saves both files based on a single sample.
To correct this error, I have pulled out the instantiations of the PrintWriter to be in the try-with-resource block of the Scanner object
import java.io.*;
import java.util.Scanner;
public class Separator {
public static final String DATAFILE = "src/etc/test.txt";
public static void main(String[] args) throws FileNotFoundException {
runData();
}
public static void runData() throws FileNotFoundException {
try (
Scanner in = new Scanner(new File(DATAFILE));
PrintWriter positive = new PrintWriter(new File(DATAFILE+"-pos"));
PrintWriter negative = new PrintWriter(new File(DATAFILE+"-neg"));
) {
// kddcup file uses '.\n' at end of each line
// setting this as delimiter which will consume the period
in.useDelimiter("[.]\r\n|[.]\n|\n");
Sample curr;
while(in.hasNext()) {
// line will hold all fields for a single sample
Scanner line = new Scanner(in.next());
line.useDelimiter(", *");
curr = new Sample(line);
if (curr.getLabel().equals("normal")) {
positive.println("GOOD");
} else {
negative.println("BAD");
}
}
}
}
}

Need help creating an array that reads and writes a .txt and lists words in alphabetical orders

I just started to code a while back and I'm in the process of dealing with arrays on my own, I understand them in theory but I need some help when it comes to getting practical. I asked my instructor to give me a couple of practices problems and he gave me the following.
using this as your main:
public static void main(String[] args) {
DatosPalabras datos = new DatosPalabras( "words.txt" );
JOptionPane.showMessageDialog(null, datos );
datos.sort();
JOptionPane.showMessageDialog(null, datos);
}
(its in spanish so bear with me) create a class named DatosPalabras and words.txt and make sure your code can:
Read and display words.txt
Display the words in "words.txt" in alphabetical order
I really appreciate the help, I'm a bit stumped but I'm curious to know how I can accomplish this. Thank you!
EDIT:
public class DatosPalabras {
public DatosPalabras(String string) {
// read and display the content of words.txt
}
public void sort() {
// need info on what to use in order to sort words instead of doubles and integers.
}
}
In this example I have 1 file named Q19505617.java. Java only allows you to have 1 public class per file. It is the class that defines the main method. So this example works only because the DatosPalabras class is contained in that file. If you need DatosPalabras to be its own class then put the DatosPalabras in its own file named DatosPalabras.java and change the class signature to be public class DatosPalabras.
import java.io.InputStream;
import java.util.Arrays;
import java.util.Scanner;
import javax.swing.JOptionPane;
public class Q19505617 {
public static void main(String[] args) {
DatosPalabras datos = new DatosPalabras("words.txt");
JOptionPane.showMessageDialog(null, datos);
datos.sort();
JOptionPane.showMessageDialog(null, datos);
}
}
class DatosPalabras {
private String[] lines;
public DatosPalabras(String filename) {
lines = new String[1];
int lineCounter = 0;
InputStream in = Q19505617.class.getResourceAsStream(filename);
Scanner scanner = new Scanner(in);
while (scanner.hasNextLine()) {
String line = scanner.nextLine();
System.out.println(line);
if(lineCounter == lines.length) {
lines = Arrays.copyOf(lines, lines.length * 2);
}
lines[lineCounter] = line;
lineCounter++;
}
}
public void sort() {
// put your real sort algorithm here. until then use this:
}
public String toString() {
StringBuilder b = new StringBuilder();
for (String line : lines) {
b.append(line).append("\n");
}
return b.toString();
}
}
You can create a reading Array like this:
String[] Array = new String[number of lines in you txt file];
int i = 0;
// Selecting the txt file
File theFile = new File("bla.txt");
//Creating a scanner to read the file
scan = new Scanner(theFile);
//Reading all the words from the txt file
while (scan.hasNextLine()) {
line = scan.nextLine();
Array[i] = line; // gets all the lines
i++;
Then you create a method for sorting.

Categories