I have to read Strings from a file which the first String is N then convert it as a Integer for a cycle for to go from 0 to N, reading each time another String from file and then convert each line read as a floatas following:
FILE Name: test.txt with the following content:
4
1.21
1.31
1.21
1.32
Java Code
public class lpa2 {
public static void main(String[] args) throws IOException {
// TODO Auto-generated constructor stub
String line;int n;
while((line = nextLine())!=null){
n = Integer.parseInt(line);
float v[] = new float[n];
for(int i = 0;i<n;i++){
String temp = readln();
v[i] = Float.parseFloat(temp);
}
for(float f:v)
System.out.println(f);
}
}
public static String readln() throws IOException{
BufferedReader bi = new BufferedReader(new InputStreamReader(System.in));
return bi.readLine();
}
}
When i use command line like this:
javac -nowarn lpa2.java
then
java lpa2 < test.txt
to use file as input i get the following error
java.lang.NumberFormatException: For input string: "{\rtf1\ansi\ansicpg1252\cocoartf1187\cocoasubrtf370"
at java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)
at java.lang.Integer.parseInt(Integer.java:492)
at java.lang.Integer.parseInt(Integer.java:527)
at lpa2.main(lpa2.java:15)
While if i try to do it using eclipse it works perfectly ....
How can i fix this? i used readln() that i created instead Scanner because i needed a faster input reader and even if i try using Scanner i get the same error ... Is there any way to fix this?
Thanks ...
Your file "test.txt" is saved as a rtf file -- I am guessing you saved it from Word or similar word processors? If you open the file in a text editor (e.g., notepad) you'll find that it doesn't contain what you expect.
Related
Using command line, I am supposed to enter a file name that contains text and search for a specific word.
foobar file.txt
I started writing the following code:
import java.util.*;
import java.io.*;
class Find {
public static void main (String [] args) throws FileNotFoundException {
String word = args[0];
Scanner input = new Scanner (new File (args[1]) );
while (input.hasNext()) {
String x = input.nextLine();
}
}
}
My program is supposed to find word and then print the whole line that contains it.
Please be specific since I am new to java.
You are already reading in each line of the file, so using the String.contains() method will be your best solution
if (x.contains(word) ...
The contains() method simply returns true if the given String contains the character sequence (or String) you pass to it.
Note: This check is case sensitive, so if you want to check if the word exists with any mix of capitalization, just convert the strings to the same case first:
if (x.toLowerCase().contains(word.toLowerCase())) ...
So now here is a complete example:
public static void main(String[] args) throws FileNotFoundException {
String word = args[0];
Scanner input = new Scanner(new File(args[1]));
// Let's loop through each line of the file
while (input.hasNext()) {
String line = input.nextLine();
// Now, check if this line contains our keyword. If it does, print the line
if (line.contains(word)) {
System.out.println(line);
}
}
}
Firest you have to open file and then read it line by line and check that word is in that line on not. see the code below.
class Find {
public static void main (String [] args) throws FileNotFoundException {
String word = args[0]; // the word you want to find
try (BufferedReader br = new BufferedReader(new FileReader("foobar.txt"))) { // open file foobar.txt
String line;
while ((line = br.readLine()) != null) { //read file line by line in a loop
if(line.contains(word)) { // check if line contain that word then prints the line
System.out.println(line);
}
}
}
}
}
Having a bit of a headache trying to parse a text file correctly, it's a pull from mysql database but the data needs to be changed a fair bit before it can be inserted again.
My program is taking a .txt file and parsing it to produce a .txt file, which is simple enough.
The issue is that it is not splitting the file correctly. The file looks as follows (the middle field of each looks strange because I've changed it to random letters to hide the real data):
(92,'xxxname',4013),(93,'sss-xxx',4047),(94,'xxx-sss',3841),(95,'ssss',2593),(96,'ssss-sss',2587),(97,'Bes-sss',2589),
I want to split it so that it produces a file like:
(92, 'xxxname',4013),
(93, 'sss-xxx', 4047),
(94, 'xxx-sss', 3841),
And so on...
Current code for parsing is as follows:
public void parseSQL(File file) throws IOException {
Scanner scanner = new Scanner(file);
while (scanner.hasNext()) {
String line = scanner.next();
String[] lines = line.split(Pattern.quote("),"));
for (String aLine : lines) {
logLine(aLine);
}
}
}
public static void logLine(String message) throws IOException {
PrintWriter out = new PrintWriter(new FileWriter("output.txt", true),
true);
out.println(message);
out.close();
}
Currently the output I'm getting is roughly on track but more split up than it should be, and of course the split method is removing the ")," which is unnecessary.
Sample of the current output:
*(1,'Vdddd
Cfffff',1989
(2,'Wdd',3710
(3,'Wfffff
Hffffff
Limited-TLC',3901
(4,'ffffffun88',2714
(5,'ffffff8',1135
(6,'gfgg8*
Been playing around for a while and have done a good bit of searching here and elsewhere but out of ideas, any help would be greatly appreciated.
You can use String.replace. There's also no need to create multiple PrintWriters and close the stream every time.
public void parseSQL(File file) throws IOException {
Scanner scanner = new Scanner(file);
PrintWriter out = new PrintWriter(new FileWriter("output.txt", true), true);
while (scanner.hasNext()) {
String line = scanner.next();
out.println(line.replace("),", ")," + System.lineSeparator()));
}
out.close();
}
The answer is simple, this line:
String line = scanner.next();
Should be:
String line = scanner.nextLine();
Thanks for your attempts folks sorry for being dumb
So I'm trying to accept a text file from the Linux command line into my Java program, but the compiler gives me that error mentioned in the title. It says the error occurs at the line that says "String fileName = args[0];". Does anyone happen to know why?
Here is my code:
public class Parsons_Decoder
{
// method: main
// purpose: receives key-phrase and sequence of integers and
// prints the secret message to the screen.
public static void main(String[] args) throws IOException
{
String fileName = args[0];
// reads incoming file (if it exists) and saves the key-phrase to
// String variable "keyPhrase"
File testFile = new File(fileName);
if(!testFile.exists())
{
System.out.println("\nThis file does not exist.\n");
System.exit(0);
}
Scanner inputFile = new Scanner(args[0]);
String keyPhrase = inputFile.nextLine();
// creates an ArrayList and stores the sequence of integers into it
ArrayList<Integer> numArray = new ArrayList<Integer>();
while(inputFile.hasNextInt())
{
numArray.add(inputFile.nextInt());
}
// decodes and prints the secret message to the screen
System.out.println();
System.out.print("Your secret message is: ");
for(int i = 0; i < numArray.size(); i++)
{
int num = numArray.get(i);
System.out.print(keyPhrase.charAt(num));
}
System.out.println("\n");
//keyboard.close();
inputFile.close();
}
}
Update:
Your professor is asking you to read in a file with stdin, using a command like the following:
java Diaz_Decoder < secretText1.txt
Your main() method should then look something like the following:
public static void main(String[] args) throws IOException {
// create a scanner using stdin
Scanner sc = new Scanner(System.in);
String keyPhrase = inputFile.nextLine();
// creates an ArrayList and stores the sequence of integers into it
ArrayList<Integer> numArray = new ArrayList<Integer>();
while (inputFile.hasNextInt()) {
numArray.add(inputFile.nextInt());
}
// decodes and prints the secret message to the screen
System.out.println();
System.out.print("Your secret message is: ");
for (int i = 0; i < numArray.size(); i++) {
int num = numArray.get(i);
System.out.print(keyPhrase.charAt(num));
}
System.out.println("\n");
}
Based on your description and the link you provided (which should be in the question, not a comment), your prof wants you to write a program that accepts the contents of a file via "standard in" (STDIN) when run as a POSIX style shell command line using redirection.
If this is indeed a requirement, you can't just read the file given as an argument, but need to change your program such that it reads from STDIN. The key concept here is that the "<" is not available to your program argument list. It will be consumed by the shell (Bash, Ksh, etc.) running the Java process, and a "pipe" setup between the file on the right side and the process on the left side. In this case, the process is your Java process running your program.
Try doing a search for "java STDIN" to get some ideas on how to write a Java program that can read its standard in.
By the way, if your program crashes with an ArrayIndexOutOfBoundError when run with redirection in this manner, it still has a bug in it. You need to test for and handle the case where you have 0 file arguments after the shell has finished processing the command line. If you want full marks, you need to handle the error and edge cases.
I have in my code a hardcoded name for a text file I am reading.
String fileName = "test.txt";
However I now have to use a command argument like so:
text.java arg1 arg2 arg3 (can be any amount) < test.txt
Can anyone help me please?
I have it getting the arguments no problem just not sure on the file. Thank you
I have tried:
String x = null;
try {
BufferedReader f = new BufferedReader(new InputStreamReader(System.in));
while( (x = f.readLine()) != null )
{
System.out.println(x);
}
}
catch (IOException e) {e.printStackTrace();}
System.out.println(x);
}
However my application now hangs on readLine, any ideas for me to try please?
That is because the file is not passed as an argument, but piped as standard input.
If that is the intended use (to pipe the content of the file), then you just have to read it from System.in (in means standard input):
public static void main(String[] args) throws IOException {
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
String firstLine = in.readLine();
// etc.
}
If you just wanted to pass the file name, then you have to remove or escape that <, because it means "pipe" in shell.
Pass the file as filename to your program and then open this file and read from it.
import java.io.*;
import java.util.*;
public class Readfilm {
public static void main(String[] args) throws IOException {
ArrayList films = new ArrayList();
File file = new File("filmList.txt");
try {
Scanner scanner = new Scanner(file);
while (scanner.hasNext())
{
String filmName = scanner.next();
System.out.println(filmName);
}
}
catch (FileNotFoundException e)
{
e.printStackTrace();
}
}}
Above is the code I'm currently attempting to use, it compiles fine, then I get a runtime error of:
java.util.NoSuchElementException
at java.util.Scanner.throwFor(Scanner.java:907)
at java.util.Scanner.next(Scanner.java:1416)
at Readfilm.main(Readfilm.java:15)
I've googled the error and not had anything that helped (I only googled the first 3 lines of the error)
Basically, the program I'm writing is part of a bigger program. This part is to get information from a text file which is written like this:
Film one / 1.5
Film two / 1.3
Film Three / 2.1
Film Four / 4.0
with the text being the film title, and the float being the duration of the film (which will have 20 minutes added to it (For adverts) and then will be rounded up to the nearest int)
Moving on, the program is then to put the information in an array so it can be accessed & modified easily from the program, and then written back to the file.
My issues are:
I get a run time error currently, not a clue how to fix? (at the moment I'm just trying to read each line, and store it in an array, as a base to the rest of the program) Can anyone point me in the right direction?
I have no idea how to have a split at "/" I think it's something like .split("/")?
Any help would be greatly appreciated!
Zack.
Your code is working but it reads just one line .You can use bufferedReader here is an example import java.io.*;
class FileRead
{
public static void main(String args[])
{
try{
// Open the file that is the first
// command line parameter
FileInputStream fstream = new FileInputStream("textfile.txt");
// Get the object of DataInputStream
DataInputStream in = new DataInputStream(fstream);
BufferedReader br = new BufferedReader(new InputStreamReader(in));
String strLine;
//Read File Line By Line
while ((strLine = br.readLine()) != null) {
// Print the content on the console
System.out.println (strLine);
}
//Close the input stream
in.close();
}catch (Exception e){//Catch exception if any
System.err.println("Error: " + e.getMessage());
}
}
}
And here is an split example class StringSplitExample {
public static void main(String[] args) {
String st = "Hello_World";
String str[] = st.split("_");
for (int i = 0; i < str.length; i++) {
System.out.println(str[i]);
}
}
}
I wouldn't use a Scanner, that's for tokenizing (you get one word or symbol at a time). You probably just want to use a BufferedReader which has a readLine method, then use line.split("/") as you suggest to split it into two parts.
Lazy solution :
Scanner scan = ..;
scan.nextLine();