I want to update content of my Text file that is created using Scanner class of Java. Each line of text file consists of 4 strings. I want to update 2 strings of every line whenever user updates values. I've tried different codes but nothing is working. Kindly help me to update my values. what should be solution?
import java.util.*;
import java.io.*;
import javax.swing.*;
public class File2
{
public static void main(String args[])
{
Scanner obj=new Scanner(System.in);
System.out.println("\f");
System.out.println("Enter Material");
String material=obj.next();
String color="Tendra Black";
System.out.println("Enter quantity");
String quantity=obj.next();
System.out.println("Enter roll");
String roll=obj.next();
Scanner fileIn = null;
try
{
fileIn = new Scanner (new FileInputStream("Stock.txt"));
}
catch(FileNotFoundException f)
{
JOptionPane.showMessageDialog(null,"File not found. Please specify coreect location.");
}
if(fileIn.hasNext())
{
while(fileIn.hasNext())
{
File log= new File("Stock.txt");
String details = fileIn.nextLine();
StringTokenizer tokenizer = new StringTokenizer(details,"-");
String materialAvailable=null;
String colorAvailable=null;
String quantityAvailable=null;
String rollAvailable=null;
while(tokenizer.hasMoreTokens())
{
materialAvailable=tokenizer.nextToken();
colorAvailable=tokenizer.nextToken();
quantityAvailable=tokenizer.nextToken();
rollAvailable=tokenizer.nextToken();
if((colorAvailable.equalsIgnoreCase(color)))
{
int val1Q=Integer.parseInt(quantityAvailable);
int val2Q=Integer.parseInt(quantity);
int val1R=Integer.parseInt(rollAvailable);
int val2R=Integer.parseInt(roll);
int quanF=val1Q+val2Q;
int rollF=val1R+val2R;
//quantityAvailable=Integer.toString(quanF);
//rollAvailable=Integer.toString(rollF);//file readTill
details=details.replaceAll(quantityAvailable,Integer.toString(quanF));
details=details.replaceAll(rollAvailable,Integer.toString(rollF));
}
try{
FileWriter fw = new FileWriter(log);
fw.write(details);
fw.close();
}
catch(Exception e){
e.printStackTrace();
}
}
}
}
}
}
You just need to open the file to overwrite instead of append, use a FileOutputStream and set the append value to false, like this
try{
FileOutputStream fw = new FileOutputStream(log, false);
fw.write(details);
fw.close();
}
Related
I am trying to read in from an input file that contains the following:
Joe Lee, 123 First Street,Omaha,MN,48217-8350
I have an array set up for the scanner to look up the lines in the input file and split them by "," so that I can get the zip code and match each number of the zip code with the items in my array. I am trying to print my output in a txt file. Here is my code:
import java.util.ArrayList;
import java.util.Scanner;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.PrintWriter;
public class BarCode {
public static void main(String[] args) {
}
public static String getBarCode(String zipcode) {
Scanner scanner = null;
try {
scanner = new Scanner(new File("addresses.txt"));
}
catch (FileNotFoundException e) {
System.out.println("Input file not found");
}
PrintWriter pw = null;
try {
pw = new PrintWriter("labels.txt");
} catch (FileNotFoundException e) {
System.out.println("Output file not found");
}
String[] barcodes = {"||:::", ":::||", "::|:|", "::||:", ":|::|",
":|:|:", ":||::", "|:::|", "|::|:", "|:|::"};
String line = scanner.nextLine();
while(scanner.hasNextLine()) {
String[] fields = line.split(",");
int code = Integer.parseInt(fields[4]);
}
}
}
So the output will read this:
Joe Lee
123 First Street
Omaha,MN,48217-8350
And then the symbols that correspond with the zip code
Solution
Fixed up your code a bit seemed a little messy. Moved your scanner and printer writer along with your loop inside your main method and then left the getBarCode method to just convert the zip code into a bar code. Hopefully this helps you.
public class BarCode {
public static void main(String[] args) {
//Scanner
Scanner scanner = null;
//Create the scanner to the text file
try {
scanner = new Scanner(new File("src/main/addresses.txt"));
} catch (Exception e) {
System.out.println("Input file not found");
}
//Create printwriter
PrintWriter pw = null;
try {
pw = new PrintWriter("labels.txt");
} catch (FileNotFoundException e) {
System.out.println("Output file not found");
}
while (scanner.hasNextLine()) {
String line = scanner.nextLine();
String[] fields = line.split(",");
//Get the fields
String name = fields[0];
String address = fields[1];
String city = fields[2];
String country_code = fields[3];
String zip_code = fields[4];
//Convert zip code to bar code string
String barcodeString = getBarCode(fields[4]);
//output the the desired output
pw.println(name);
pw.println(address);
pw.println(city+", "+country_code+", "+zip_code);
pw.println (barcodeString);
}
//Close the file to print the data
pw.close();
}
public static String getBarCode(String zipcode) {
//Barcode string
String barcode = "";
//Barcode array
String[] barcodes = {"||:::", ":::||", "::|:|", "::||:", ":|::|",
":|:|:", ":||::", "|:::|", "|::|:", "|:|::"};
//Get zip code and replace '-'
zipcode = zipcode.replace("-", "");
//To char array
char[] numbers = zipcode.toCharArray();
//Append array values to barcode string
for (int i = 0; i < numbers.length; i++) {
barcode += barcodes[Integer.parseInt(String.valueOf(numbers[i]))];
}
return barcode;
}
}
Output
Joe Lee
123 First Street
Omaha, MN, 48217-8350
:|::||::|:::|:|:::|||:::||::|:::||::|:|:||:::
I'm trying to learn java but I don't know why I'm getting there errors.What I basically want is that user will input new characters and will be written to the file as long it is not the word "stop"(program terminates at this point).
Can you guys help me?
import java.io.*;
import java.util.*;
class FileHandling{
public static void main(String args[]){
System.out.println("Enter a File name");
Scanner input = new Scanner(System.in);
String file1Name = input.next();
if(file1Name == null){
return;
}
try{
File f1 = new File(file1Name+".txt");
f1.createNewFile();
String file1NameData = "";
String content = input.next();
FileWriter fileWritter = new FileWriter(f1.getName(),true);
BufferedWriter bufferWritter = new BufferedWriter(fileWritter);
while(!(file1NameData=bufferWritter.readLine()).equalsIgnoreCase("stop")){
bufferWritter.write(file1NameData + System.getProperty("line.separator"));
}
bufferWritter.write(file1NameData);
bufferWritter.close();
}catch(Exception e){
System.out.println("Error : " );
e.printStackTrace();
}
}
}
You are trying to read from writer which you can't. You already have scanner and using it, you could read form System input i.e. Keyboard.
Change your line like:
From
while(!(file1NameData=bufferWritter.readLine()).equalsIgnoreCase("stop")){
To
while(!(file1NameData=input.nextLine()).equalsIgnoreCase("stop")){
You are trying to read from your output, not your input
while(!input.next().equalsIgnoreCase("stop")){
bufferWritter.write(file1NameData + System.getProperty("line.separator"));
}
public static void main(String[] args) throws Exception {
try (BufferedReader reader = new BufferedReader(new InputStreamReader(System.in))) {
try (BufferedWriter writer = new BufferedWriter(new FileWriter(new File("test.txt"), true))) {
String line = null;
while ((line = reader.readLine()) != null) {
if (line.equals("stop"))
break;
writer.write(line);
writer.newLine();
}
}
}
}
I am trying to make a program that imports a text file and analyzes it to tell me if another text file has possible match up sentences. I keep running into this error when I import my file and attempt to analyze it. I am assuming that I am missing something in my code.
Exception in thread "main" java.util.NoSuchElementException
at java.util.Scanner.throwFor(Scanner.java:907)
at java.util.Scanner.next(Scanner.java:1416)
at PossibleSentence.main(PossibleSentence.java:30)
Heres my code too:
import java.util.Scanner;
import java.io.File;
import java.io.FileNotFoundException;
public class PossibleSentence {
public static void main(String[] args) throws FileNotFoundException{
Scanner testScan = new Scanner(System.in);
System.out.print("Please enter the log file to analyze: ");
String fileName = testScan.nextLine();
File f = new File(fileName);
Scanner scan = new Scanner(f);
String line = null;
int i = 0;
while (scan.hasNextLine()) {
String word = scan.next();
i++;
}
scan.close();
File comparative = new File("IdentifyWords.java");
Scanner compare = new Scanner(comparative);
String line2 = null;
}
}
The second scanner I havent completed yet either. Any suggestions?
We need more info to conclusively answer, but check out the documentation for next(). It throws this exception when there's no next element. My guess is it's because of this part:
String fileName = testScan.nextLine();
You're not checking if hasNextLine first.
You are passing a file argument to a Scanner object, try using an InputStream
File input = new File(/* file argument*/);
BufferedReader br = null;
FileReader fr= null;
Scanner scan = null;
try {
fr = new FileReader(input);
br = new BufferedReader(fr);
scan = new Scanner(br);
/* Do logic with scanner */
} catch (IOException e) {
/* handling for errors*/
} finally {
try {
if (br != null) {
br.close();
}
if (fr != null) {
fr.close();
}
if (scan != null) {
scan.close();
}
} catch (IOException e) {
/* handle closing error */
}
}
This question already has an answer here:
Reading a File From the Computer
(1 answer)
Closed 8 years ago.
I'm trying to read a file from the computer that is in the same folder as the source code and when I run the code is saying: File does not exist
Can you help me ?
import java.io.*;
import java.util.*;
public class Lotto1 {
static String[][] arr;
static String name, number;
public static void main(String[] args) throws IOException {
File f = new File("D:\\Filipe\\Project Final\\src\\database_lotto.txt.txt");
Scanner s;
try {
s = new Scanner(f);
BufferedReader reader = new BufferedReader(new FileReader(f));
int lines = 0;
while(reader.readLine() != null) {
lines++;
}
reader.close();
arr = new String[lines][3];
int count = 0;
//while theres still another line
while(s.hasNextLine()) {
arr[count][0] = s.next() + "" + s.next();
arr[count][1] = s.next();
arr[count][2] = s.next();
count++;
}
} catch(FileNotFoundException ex) {
System.out.println("File does not exist");
}
I've inferred what you're trying to do and recoded it, but this implementation will read the file if it is where you say it is.
public static void main(String[] args) {
final String filename = "database_lotto.txt";
final File lottoFile = new File(filename);
try (final Scanner scanner = new Scanner(lottoFile)) {
final List<String[]> storage = new ArrayList<String[]>();
while (scanner.hasNextLine()) {
storage.add(scanner.nextLine().split(" "));
}
}catch (FileNotFoundException ex) {
System.out.println("File not found :(");
}
}
Are you on Unix/Linux machine?
It is better to use File.separator instead of \, because File.separator uses the system char for a directory (\ on Win, / on Linux etc.)
Use File.exists() to check if file is there, before using it.
hey i need the code to replace all the occurrence of conjunctions in a txt file by end of line. I have a list of conjunctions saved in a txt file.i want both the input file taken and the conjunctions file to be stored in an array form.Then using for loop i wanted compare both the arrays .but this gives many errors.is there a better way to do the same?
this is what i tried doing, but it shows error in the for loop
import java.util.List;
import java.util.Scanner;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JFileChooser;
public class Toarray
{
private static Object arrays;
public static void main(String args[]) throws FileNotFoundException
{
String filename,path;
System.out.println("select the input file");
JFileChooser chooser = new JFileChooser();
chooser.showOpenDialog(null);
File file1 = chooser.getSelectedFile();
chooser.showOpenDialog(null);
filename = file1.getName();
path= file1.getPath();
Scanner sc;
sc = new Scanner(new File(filename));
List<String> lines = new ArrayList<String>();
while (sc.hasNextLine()) {
lines.add(sc.nextLine());
}
String[] inp = lines.toArray(new String[0]);
for (int index=0;index<=20;index++ ){
System.out.println(inp[index]);}
String remove;
remove="/Machintosh HD/Users/vaishnavi/Desktop/temp.txt";
Scanner sc1;
sc1 = new Scanner(new File(remove));
List<String> con;
con = new ArrayList<String>();
while (sc1.hasNextLine()) {
lines.add(sc1.nextLine());
}
String[] conj = con.toArray(new String[0]);
}
StriString oldtext;
for(int i=0;i<=55;i++)
{
for(int j=0;j<=75;j++)
{
if( inp[i].equals(conj[j]))
{
String newtext = oldtext.replaceAll(inp[i], ".");
FileWriter writer = null;
try {
writer = new FileWriter(path);
} catch (IOException ex) {
Logger.getLogger(Toarray.class.getName()).log(Level.SEVERE, null, ex);
}
try {
writer.write(newtext);
} catch (IOException ex) {
Logger.getLogger(Toarray.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
}
}
please do help :)
To check if array contains something or not try this:
if(Arrays.asList(inp).contains("something")){
//Do something
}