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
}
Related
I try to combine information spread across different files, generating a new ArrayList with information somehow based on the original files, and output a new txt which contains the first word of each element of that ArrayList. The problem is my code doesn't end for some reason, and I don't know why.
Here is my code:
import java.util.Scanner;
import java.util.ArrayList;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.PrintWriter;
import java.io.IOException;
public class FileReadVaryingAmount {
public static void main(String[] args) throws IOException {
ArrayList<FileInputStream> files = getStreams("letters.txt");
writeFirstWords(files, "myoutput.txt");
}
public static ArrayList<FileInputStream> getStreams(String filenames) {
FileInputStream fis;
Scanner sc;
ArrayList<FileInputStream> inFS = new ArrayList<>();
try {
fis = new FileInputStream(filenames);
sc = new Scanner(fis);
}
catch (Exception e) {
System.out.println("File open error");
return inFS;
}
Scanner scnr = new Scanner(System.in);
try {
while(scnr.hasNextLine()){
String name = scnr.next();
try {
FileInputStream temp = new FileInputStream(name);
Scanner scanner = new Scanner(temp);
while (scanner.hasNext()){
inFS.add(new FileInputStream(scanner.next()));
}
}
catch (Exception e) {
System.out.println("Error.");
}
}
}
catch(Exception e){
System.out.println("Error.");
}
return inFS;
}
public static void writeFirstWords(ArrayList<FileInputStream> list, String outfileName) {
FileOutputStream fileByteStream = null;
PrintWriter outFS = null;
try {
fileByteStream = new FileOutputStream(outfileName);
outFS = new PrintWriter(fileByteStream);
}
catch (Exception e) {
System.out.println("File open error");
}
for (int i = 0; i < list.size(); i++){
outFS.println(list.get(i));
}
outFS.flush();
try {
fileByteStream.close();
outFS.close();
}
catch (Exception e) {
System.out.println("File close error");
}
}
}
and here is the content of the files:
letters.txt
myfile.txt
myfile2.txt
myfile3.txt
myfile.txt
101 102
myfile2.txt
5 101 102 103 104 105
myfile3.txt
1 2 3 4 5
I revised your code and now it works perfectly.
public static void main(String[] args) throws IOException
{
final ArrayList<String> firstWords = getFirstWords("letters.txt");
for (String word : firstWords)
{
System.out.println(word);
}
}
public static ArrayList<String> getFirstWords(String path) throws IOException
{
final ArrayList<String> firstWords = new ArrayList<>();
final BufferedReader input = new BufferedReader(new FileReader(path));
// loop through all lines of the file
String line;
while ((line = input.readLine()) != null)
{
// the line corresponds to another file path
// first line = myfile.txt
// second line = myfile2.txt
// third line = myfile3.txt
firstWords.add(getFirstWordInFile(line));
}
input.close();
return firstWords;
}
public static String getFirstWordInFile(String path) throws IOException
{
final BufferedReader input = new BufferedReader(new FileReader(path));
// read the first line of the file
final String firstLine = input.readLine();
// split this line into separate words
final String[] words = firstLine.split(" ");
final String firstWord = words[0];
input.close();
return firstWord;
}
The output is:
101
5
1
So what my code does is, checks whether the file has certain number of columns. if the columns are less than the specified amount of columns it adds the string "null" from the next line.
Furthermore, the code copies the content in file "text" using org.apache.io and puts it into new file named "test".
(content in file "text is in two rows").
I want the content to be shown in file "test" in a single line.
package MySQL;
import java.io.*;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.*;
import org.apache.commons.io.*;
public class Add {
public static void main(String args[]) throws IOException {
File file = new File("C:\\Users\\dhruv\\Desktop\\Practicals\\IntelliJ\\src\\MySQL\\text.txt");
Scanner scanner = null;
try {
scanner = new Scanner(file);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
int number = 0;
if (scanner.hasNextLine()) {
number = scanner.nextLine().split(" ").length;
}
System.out.println(number);
scanner.close();
if (number < 10) {
FileWriter bw_1 = new FileWriter("C:\\Users\\dhruv\\Desktop\\Practicals\\IntelliJ\\src\\MySQL\\text.txt", true);
BufferedWriter bw = new BufferedWriter(bw_1);
PrintWriter out = new PrintWriter(bw);
for (int i = 0; i < 10-number; i++)
{
out.write("Null");
out.write(" ");
}
out.close();
}
File file_1 = new File("C:\\Users\\dhruv\\Desktop\\Practicals\\IntelliJ\\src\\MySQL\\text.txt");
String content = null;
try {
content = FileUtils.readFileToString(file, StandardCharsets.UTF_8);
} catch (IOException e) {
e.printStackTrace();
}
System.out.println(content);
Path path = Paths.get("C:\\Users\\dhruv\\Desktop\\Practicals\\IntelliJ\\src\\MySQL\\test.txt");
//String contents = ;
try {
Files.writeString(path, content, StandardCharsets.UTF_8);
} catch (IOException ex) {
}
}
}
"text" file
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();
}
I'm new at java I would like to know how to read a .txt file and then put every single line in an array cell.
.txt file must be formatted as shown:
car //goes in array[0]
boat //goes in array[1]
ship //goes in array[2]
airplane //goes in array[3]
//...and so on..
I've already tried to create a ReadFile class implemented in this way:
import java.io.*;
import java.util.*;
public class ReadFile {
private Scanner x;
public void open(){
try{
x = new Scanner(new File("time_table_data.txt"));
}catch(Exception e){
System.out.println("Could Not Create The File");
}
}
public String read(){
String s = "";
while(x.hasNext()){
String a = x.next();
s = a.format("%s\n",a);
}
return s;
}
public void close(){
x.close();
}
}
The problem is that you don't know how many words there are coming. To solve that, you could use an ArrayList.
List<String> entries = new ArrayList<String>();
while (scanner.hasNext())
{
entries.add(scanner.nextLine());
}
System.out.println(entries);
Access them using the get(int index) method:
String test = entries.get(0); // This will be "car"
if you're willing to use Apache Commons IO then you can do this really easy:
import org.apache.commons.io.FileUtils;
String[] linesArr = new String[0];
List<String> lines = FileUtils.readLines(new File("FILE_NAME.txt"));
if (lines != null) {
linesArr = lines.toArray(linesArr);
}
Just do:
List<String> lines = new ArrayList<String>();
try (BufferedReader br = new BufferedReader(new FileReader(file))) {
String line;
while ((line = br.readLine()) != null) {
lines.add(line); // Add line to list
}
} // Try-with-resources closes reader
You don't need the scanner or anything else fancy when you just looking for whole lines.
If you really need an array not a list at the end you can just read out the array from the final List.
Make a method that reads all data from file and stores in a List as follows.
public ArrayList<String> fileRead(String fileName){
File f;
String s;
FileReader fr = null;
BufferedReader br = null;
ArrayList<String> sl = new ArrayList<String>();
try {
f = new File(fileName);
fr = new FileReader(f);
br = new BufferedReader(fr);
while((s=br.readLine())!=null){
sl.add(s);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}finally{
try {
if(br!=null)
br.close();
if(fr!=null)
fr.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return sl;
}
Like a similar project I made, this project is reading characters from a txt file, reversing the order of the string and rewriting it to another txt file. But it keeps outputting my exception of "Something went wrong". Can anyone help me fix what is going wrong?
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Scanner;
public class ReverseFile
{
public static void main(String[] args) throws IOException
{
try{
String source = args[0];
String target = args[1];
File sourceFile=new File(source);
Scanner content=new Scanner(sourceFile);
PrintWriter pwriter =new PrintWriter(target);
while(content.hasNextLine())
{
String s=content.nextLine();
StringBuffer buffer = new StringBuffer(s);
buffer=buffer.reverse();
String rs=buffer.toString();
pwriter.println(rs);
}
content.close();
pwriter.close();
System.out.println("File is copied successful!");
}
catch(Exception e){
System.out.println("Something went wrong");
}
}
}
So here is the information from the stacktrace:
java.lang.ArrayIndexOutOfBoundsException: 0
at ReverseFile.main(ReverseFile.java:36)
i am not so sure about your environment, and how long the text might be. and i am also not so sure why you need a scanner?
anyway, here's my take on the problem, hope this helps you :)
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.io.RandomAccessFile;
import java.io.Reader;
public class Reverse {
public static void main(String[] args) {
FileInputStream fis = null;
RandomAccessFile raf = null;
// by default, let's use utf-8
String characterEncoding = "utf-8";
// but if you pass an optional 3rd parameter, we use that
if(args.length==3) {
characterEncoding = args[2];
}
try{
// input file
File in = new File(args[0]);
fis = new FileInputStream(in);
// a reader, because it respects character encoding etc
Reader r = new InputStreamReader(fis,characterEncoding);
// an outputfile
File out = new File(args[1]);
// and a random access file of the same size as the input, so we can write in reverse order
raf = new RandomAccessFile(out, "rw");
raf.setLength(in.length());
// a buffer for the chars we want to read
char[] buff = new char[1];
// keep track of the current position (we're going backwards, so we start at the end)
long position = in.length();
// Reader.read will return -1 when it reached the end.
while((r.read(buff))>-1) {
// turn the character into bytes according to the character encoding
Character c = buff[0];
String s = c+"";
byte[] bBuff = s.getBytes(characterEncoding);
// go to the proper position in the random access file
position = position-bBuff.length;
raf.seek(position);
// write one or more bytes for the character
raf.write(bBuff);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
// clean up
try {
fis.close();
} catch (Exception e2) {
}
try {
raf.close();
} catch (Exception e2) {
}
}
}
}
You need to specify the filenames(source and target) on command-line, while running the program.
java ReverseFile source.txt target.txt
In your program, you try to read the name of files from command-line as
String source = args[0];
String target = args[1];
So if you do not specify those names there, java tries to access the array args at index 0 and 1 which are empty and you get ArrayIndexOutOfBoundsException.
here is ur error free solution to ur problem,u were using "Scanner" without importing "util"
package.here we go:-----------
import java.io.*;
import java.util.*;
public class ReverseFile
{
public static void main(String[] args) throws IOException
{
try{
File sourceFile=new File(args[0]);
Scanner content=new Scanner(sourceFile);
PrintWriter pwriter =new PrintWriter(args[1]);
while(content.hasNextLine())
{
String s=content.nextLine();
StringBuffer buffer = new StringBuffer(s);
buffer=buffer.reverse();
String rs=buffer.toString();
pwriter.println(rs);
}
content.close();
pwriter.close();
System.out.println("File is copied successful!");
}
catch(Exception e){
System.out.println("Something went wrong");
}
}
}
Just thought of a simple approach.
public class ReadFileReverse {
public int[] readByte(File _file) throws IOException {
FileInputStream source = new FileInputStream(_file);
int currentByte = source.available();
int readCount = 0;
int byteContainer[] = new int[currentByte];
while(readCount < currentByte){
byteContainer[readCount] = source.read();
readCount++;
}
source.close();
return byteContainer;
}
public void printReverse(int[] fileContent){
for(int byt=fileContent.length -1; byt >= 0 ; byt--){
System.out.print((char) fileContent[byt]);
}
}
public static void main(String[] args) throws IOException {
File fileToRead = new File("/README.txt");
ReadFileReverse demo = new ReadFileReverse ();
int[] readBytes = demo.readByte(fileToRead);
demo.printReverse(readBytes);
}
}
Here we are reading a file in string variable, then making a String Builder object to perform reverse operation efficiently, then printing
package com;
import java.io.FileReader;
public class Main {
public static void main(String[] args) {
try {
FileReader fr = new FileReader("D:\\newfile.txt");
String str = "";
int ch;
//reading characters in to string variable
while ((ch = fr.read()) != -1) {
str += Character.toString((char) ch);
}
System.out.println("Original String : " + str);
//converting string variable to String Builder object
StringBuilder sb = new StringBuilder(str);
//reversing the string and printing
System.out.println("Reverse order : " + sb.reverse());
fr.close();
} catch (Exception e) {
System.out.println("error");
}
}
}
Output: