Reading File To String With Stdin Redirection?
Feb 6, 2015
I'm working on a project in which I need to read an entire block of text from a file, modify the text, and store the text into a character array. This wouldn't seem so bad, except I have to do this through the command line.
For example, in the terminal:
java program < input.txt
runs the program and uses data from input.txt.
I've considered using an input stream, but most tutorials on reading from a file involve creating a file object such as
FileInputStream fis = new FileInputStream("input.txt");
I'm not supposed to include the file name in the code. I'm not supposed to ask for the file name either.
I've used code such as
final static int MAX = 10000;
public static void main(String[] args) throws IOException {
// TODO code application logic here
InputStreamReader stdin = new InputStreamReader(System.in);
char[] cbuf = new char[MAX];
stdin.read(cbuf);
String str = cbuf.toString();
System.out.println(str);
}
This does store the text into an array, but I need to make adjustments to the text. Using toString prints a memory address.
storing data from an input stream into a string or an array using redirection so that I can then modify the contents of the string/array later on in the program?
View Replies
ADVERTISEMENT
Mar 22, 2015
How do I read in a file line by line into an array without using arraylist?
I know how to do this using BufferedReader, but I am wondering how to do this using Scanner? When I used BufferedReader I noticed that there must be two exceptions to be caught which were IOException and FileNotFoundException, whereas a Scanner needs only a FileNotFoundException, why is that?
Java Code: public class practice {
public String[] array;
Scanner inputStream = null;
Scanner n = new Scanner(System.in);
public String line;
[Code].....
View Replies
View Related
Aug 6, 2014
Show me a code where I can get text file all content to String?
View Replies
View Related
Dec 6, 2014
I am having issues insert each line of the simple textfile into a specific varible I want it to go to. For example my text file is ordered like this
Dallas
78 F
North, 15 mph
dallasimage
Denver
29 F
South, 10 mph
denverimage
and I want Dallas in city variable, 78f in temperature variable, and so on until text ends, at the moment is all goes into city variable, it all prints from there! I tried inserting it into an array but it would read all the lines previous to it in addition to reusing readline and all failed.
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
public class Textreader {
public static void main(String[] args) {
[code]....
View Replies
View Related
Apr 1, 2015
I have the following code which will call the server through HttpUrlConnection.
1)
String response = HttpUtil.submitRequest(json.toJSONString(), "http://ipaddr:port/SessionMgr/validateSession?sessionId=_78998348uthjae3a&showLoginPage=true");
The above lines will call the following code:
2)
public static String submitRequest(String request, String **requestUrl**) {
try {
URL url = new URL(requestUrl);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setDoOutput(true);
[Code] ......
In the above code the form should go to the servlet as mentioned in the actionUrl, but it is again going to servlet which is in step(1).
1) May i know can we make this above html form in step(3) to submitted and redirect to the servlet in **actionUrl**.
As per the above code i am summarizing the requirement. If the session is null, I have to redirect the user to login page and validated against database and then the response should go to step(1), Is it possible?
View Replies
View Related
Dec 9, 2014
I am working on a project that requires me to build a database with random access file, representing products, the base product contains a name (about 30 characters), a price (double), and a quantity (integer). I have worked on this project for probably 15+ hours and have tried so many things and feel like I've barley made any progress...
The part i am really struggling with is taking the data from the text file and creating an object array with it using the product class. Once ive accomplished that, i have to use that data to create a random access file with the data. Here is the base Product class that must be used to create the objects for the array.
public class Product
{
public String pName;
public String stringName;
public double price;
public int quanity;
[Code]...
these continue for about 40-50 entries, they are not seperated by a blank line though i had to add those so it would display correctly, each entry is on its own line with name seperated with spaces, then price after a comma, then quanity after the second comma.....
View Replies
View Related
Dec 8, 2014
I am working on a project that requires me to build a database with random access file, representing products, the base product contains a name (about 30 characters), a price (double), and a quantity (integer). I have worked on this project for probably 15+ hours and have tried so many things and feel like I've barley made any progress...
The part i am really struggling with is taking the data from the text file and creating an object array with it using the product class. Once ive accomplished that, i have to use that data to create a random access file with the data.
Here is the base Product class that must be used to create the objects for the array.
public class Product
{
public String pName;
public String stringName;
public double price;
public int quanity;
//Constructor
public Product( String pName, double price, int quanity )
[code]....
and then here is the data from the text file that i must extract to use to create product objects.
Dill Seed,938,34
Mustard Seed,100,64
Coriander Powder,924,18
Turmeric,836,80
Cinnamon (Ground Korintje),951,10
Cinnamon (Ground) Xtra Hi Oil (2x),614,31
Cinnamon (Ground) High Oil (1X),682,19
these continue for about 40-50 entries, they are not separated by a blank line though i had to add those so it would display correctly, each entry is on its own line with name separated with spaces, then price after a comma, then quanity after the second comma.....
View Replies
View Related
Apr 7, 2015
The project is a program that allows the user to enter students and enter grades for each student. One of the requirements is that if there is already a grade stored for the student that it will display the previous grade. IF the user then enters a new grade the new grade will be stored. IF the user simply presses enter (enters an empty string) nothing is done. I have everything working except for the requirement of doing nothing if the user enters an empty string. If I just press enter at this point I get a NumberFormatException.
The below code is a method "setTestGrades" from the student class. This method iterates through each student object stored in an array list and then checks if there is a previous grade (Requirement# unset grades have to default to -1) before allowing the user to set a new grade.
public void setTestGrades(int testNumber) { //Sets the grade for the specified test number for each student in the arraylist.
testNumber -= 1;
Scanner input = new Scanner(System.in);
for (int i = 0; i < studentList.size(); i++) {
System.out.println("Please enter the grade for Test #" + (testNumber + 1) + " For Student " + studentList.get(i).getStudentName());
[code]....
View Replies
View Related
Jan 18, 2014
I have a CSV file with 16K entries of a data table. Does Java work well with CSV file? So I found this code. And it seems its quite easy to read in the data I need. Say for example if I wanted a loop to randomly pick the first field of a specific line in the CSV data table. How would i go about coding that??????
package cvs.test;
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
[code]....
The CSV looks like the above. and I basically would like to read in the Hand to get it to show in a text box and then randomly have the program ask me to correctly identify the True/False return for one of the SB/BB/UG/MP/CO/BN columns.
View Replies
View Related
Mar 3, 2013
how to get the first few hex symbols of a file in java, for example if i input a pdf into my coding i want my program to output, e.g "25 46 44 38" ....
I have been able to print out the hex of a whole file but not managed to set a maximum read limit so that my code only takes a certain amount of values ....
View Replies
View Related
Mar 21, 2014
I am implementing a recursive descent parser that recognizes strings in the language below. The input should be from a file "input.txt" and output should be to the console.
The grammar:
A -> I = E | E
E -> T + E | T - E | T
T -> F * T | F / T | F
F -> P ^ F | P
P -> I | L | UI | UL | (A)
U -> + | - | !
I -> C | CI
C -> a | b | ... | y | z
L -> D | DL
D -> 0 | 1 | ... | 8 | 9
An example session might look like this:
String read from file: a=a+b-c*d
The string "a=a+b-c*d" is in the language.
String read from file: a=a**b++c
The string "a=a**b++c" is not in the language.
Java Code: /**
* The Grammar
* A -> I = E | E
*E -> T + E | T - E | T
*T -> F * T | F / T | F
*F -> P ^ F | P
*P -> I | L | UI | UL | (A)
*U -> + | - | !
[code]....
My current output looks like this:
Java Code: The string read from file: a=a+b-c*d
The string "" is not in the language. mh_sh_highlight_all('java');
So it seems to be reading the input file correctly. My error seems to be on this part
Java Code: s = args.length == 1 ? args[0] : ""; mh_sh_highlight_all('java');
When I put the string in that line such as: s = args.length == 1 ? args[0] : "a=a+b-c*d";
My output is:
Java Code: The string read from file: a=a+b-c*d
The string "a=a+b-c*d" is in the language. mh_sh_highlight_all('java');
How can I go about it reading the string from the input file though?
Also, I am not too sure my boolean functions for P, I and, L are correct. Mainly when two terms are together (UI, UL, CI, DL).
View Replies
View Related
Jan 27, 2013
I am trying to read a content of file downloaded from ftp and return it as a String. This is what I use:
Java Code:
import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.InputStream;
import org.apache.commons.net.ftp.FTPClient;
public class Test {
public static void main(String [] args) throws IOException{
FTPClient ftp = new FTPClient();
[code]....
The code does not work, although all the links are correct.
View Replies
View Related
Oct 22, 2014
I have to read from a file that is formatted like that :
name
status
friend
END
name
status
friend
END
.. etc
could be more than one line of friends, which where I have my problem. I can't get it to check if after the friend name the word "END"
I have tried to write a while loop inside the main while loop but it didn't work, and now I have tried to check that in a separate function which it also failed, thats my two while loops
BufferedReader br = null;
FileReader fr = null;
int getLine = 0;
try {
String line;
fr = new FileReader(fileName);
br = new BufferedReader(fr);
[Code] .....
Most of the time I got nullPointerException or missed up order for printing the file !!
View Replies
View Related
Sep 9, 2014
I've looked at multiple sources and everyone is saying different stuff. Which one should I be using? FileWriter/FileReader, other people was saying PrintWriter, and one even said : "Formatter" which is the one I'm doubting mostly. My purposes for writing files is for like saving maps, saving high scores, etc.
View Replies
View Related
Mar 29, 2014
I'm new to Java and have not been able to figure this out. I'm reading a text file that contains this:
110001 commercial 500000.00 101
110223 residential 100000.00 101
110020 commercial 1000000.00 107
110333 land 30000.00 105
110442 farm 200000.00 106
110421 land 40000.00 107
112352 residential 250000.00 110
The output goes to a text file and should look like this:
COMMERICAL
FARM
LAND
RESIDENTIAL
101 600000.00
105 30000.00
106 200000.00
107 1040000.00
110 250000.00
I'm creating the output file, but it only contains the categories and not the details below them. Cant seem to figure out why.
Java Code:
package propertylistings;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;
[Code] ....
View Replies
View Related
Oct 6, 2014
I am trying to read from a text file that has that contains a list of stock tickers and pairs letting the user choose a ticker and provide analysis of stock. Given a ticker from the user provide
1) the max price, the min price and the avg price of the stock from all lines in the file.
2)Additionally the user should be able to find the stock with the highes price as well as the lowest price in the list.
3)lastly the user should be able to specify a different filename for the stock file.
Im trying to do part 1 and I am having trouble trying to read the whole text file and outputting the stock price with the max,min and avg. Am I heading towards the right track at least? Keep in mind I have just attempted trying to read the text file I have and not tried to find the max or min or avg Right now my code is crashing when I enter the stock ticker that is my primary concern.
package hw01b;
import java.util.Scanner;
import java.io.*;
public class Hw01b
{
static Scanner in = new Scanner(System.in);
static Scanner console = new Scanner(System.in);
[Code] .....
View Replies
View Related
Feb 20, 2014
Write a program that extracts words from a file. For the purposes of this program, a word is defined as a series of adjacent letters. Only print words that are at least four and no more than 12 letters long. Print each word on a different line.
The program should read the name of the file from the keyboard.
************************************************** ************************************************** **************
I need to get the filename from the user for this particular program. Usually I would have the name of the file prewritten into the source code like this....
Scanner input = new Scanner(new File("gettsy_burg.txt");
I tried different ways but I just can't seem to figure it out.... I guess what I'm really asking is how to rearrange Scanner input = new Scanner(new File("gettsy_burg.txt"); since I want the user to input the filename instead of the filename being prewritten by the programmer(me).
This is what I have so far to let the user for input....
Scanner keys = new Scanner(System.in);
System.out.println("Enter the filename: ");
String fileName = keys.nextLine();
keys = new Scanner(new File(fileName));
View Replies
View Related
Feb 28, 2014
I'm trying to read a .txt file and put each line in a array of strings but it's not working! What is wrong with this code?He stops in "while" loop.
import java.io.File;
import java.io.FileReader;
import java.io.BufferedReader;
import java.lang.Character;
import java.lang.String;
[code]...
View Replies
View Related
Feb 20, 2014
Write a program that extracts words from a file. For the purposes of this program, a word is defined as a series of adjacent letters. Only print words that are at least four and no more than 12 letters long. Print each word on a different line.
The program should read the name of the file from the keyboard.
************************************************** ************************************************** **************
I need to get the filename from the user for this particular program. Usually I would have the name of the file prewritten into the source code like this....
Scanner input = new Scanner(new File("gettsy_burg.txt");
I tried different ways but I just can't seem to figure it out....
View Replies
View Related
Jan 10, 2014
I have accountsData.txt file in my default package, this is the file it should be writing to and reading from.
There is an ATM class, which has the main in it. From here the program is supposed to work like an atm, you type in your account number and can withdraw or deposit. It is supposed to then write the changes to the file.
//Read from a file.
public void loadAccounts(String inputFileName) throws IOException
{
Scanner fin = new Scanner(new File(inputFileName));
// Variables to store the values.[/color]
int account = 0;
double balance = 0.0;
[Code] .....
View Replies
View Related
Apr 26, 2010
What I am trying to use this code for is to scan the files for a match that was typed with the corresponding name. here is what i have:
import java.util.Scanner;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
[code]...
View Replies
View Related
Mar 18, 2015
package project3;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
[code]....
method countMail!! Also the text file you are reading from is attached as ampo_uumail.txt and i also have a picture of the output.
View Replies
View Related
Sep 22, 2014
Im trying to read a file called m1 and put that information into a 2-D array with the first two numbers being the size of the array i was able to set the size of the array but how do i populate array?
import java.util.Scanner;
import java.io.*;
public class test{
public static void main(String [] args)throws IOException{
Scanner fr = new Scanner(new File("m1.txt"));
String line = fr.nextLine();
[code]....
View Replies
View Related
Jul 19, 2014
This what the data file looks like -
5165168416516988798484984984984984
9898798798798
1556516846516518498
51688484979789798798798491
The problem was to make code which will combine consecutive lines which contain some data into one line and print it. I made a solution that works.
import java.io.File;
import java.io.FileNotFoundException;
import java.util.NoSuchElementException;
import java.util.Scanner;
public class Filez {
public static void main(String[] args) {
File file = null;
[code]...
View Replies
View Related
May 26, 2014
So I have a text file, and I want my Java program to store names from the text file. How do I do that? This is what I have so far.
Java Code: import java.util.Scanner;
import java.io.File;
BingoCard[] cards = new BingoCard[n]; //Array of BingoCard objects, n being the length of the Array
Scanner sc = new Scanner(File("Names")); //Names is the name of the file
for(int c = 0; c < cards.length; c++)
cards[c] = new BingoCard(sc.nextLine); mh_sh_highlight_all('java');
Here's the constructor.
Java Code: private string myName;
public BingoCard(String name)
{
myName = name;
} mh_sh_highlight_all('java');
Whenever I compile, I get this error message.
View Replies
View Related
May 2, 2014
I'm trying to print the number of vertices in a text file on a graph which is the first integer in the file and then the type of graph is an undirected graph for a 0 or a 1 for a directed graph. Right now I'm just trying to print the number of vertices which is a 6 in the text file.
Here's the text file:
6,1
0,2 0,4 1,4 1,5 2,1 2,3 2,5 3,2 3,4 4,1 4,5 5,1 5,3 5,2
Im getting the following error:
Exception in thread "main" java.lang.IndexOutOfBoundsException: Index: 6, Size: 0
at java.util.ArrayList.rangeCheckForAdd(Unknown Source)
at java.util.ArrayList.add(Unknown Source)
at Vertices.main(Vertices.java:21)
Then I need to know how to go about reading the next line in the file, do you read it with the nextLine and put it into an arrayList or do I read each index in the graph?
public class Vertices
{
public static void main(String[] args) throws Exception
{
Scanner inFile = new Scanner(new File("graphs.txt"));
// Read the number of vertices
String line = inFile.nextLine();
ArrayList<Integer> list=new ArrayList<Integer>();
String[] data=line.split("[\,]");
int numberofvertices=Integer.parseInt(data[0]);
int typeOfGraph=Integer.parseInt(data[1]);
list.add(numberofvertices,typeOfGraph);
System.out.println("The number of vertices is " + numberofvertices);
}
}
View Replies
View Related