I want to interchange two words in a given java file - java

I want to interchange the last 2 words in a java file.
The file is called text_d.txt and it contains:
Student learns programming java.
and this is the code(below).The output is the same and I don't understand why it does not change.
import java.nio.*;
import java.io.*;
import java.lang.*;
public class Test3 {
public static void main(String[] args) throws Exception {
String s2="text_t.txt";
File _newf = new File("text_d.txt");
changeOrder(_newf);
}
public static void changeOrder(File f) throws Exception {
FileInputStream _inp=new FileInputStream(f.getAbsolutePath());
BufferedReader _rd=new BufferedReader(new InputStreamReader(_inp));
String _p=_rd.readLine();
while (_p != null) {
String [] _b = _p.split(" ");
for(int i = 0; i <= _b.length; i++) {
if(i == 2) {
String aux=_b[i];
_b[i]=_b[i+1];
_b[i+1]=aux;
break;
}
}
_p=_rd.readLine();
}
}
}

For reading, interchanging and writing the file, I suggest you to do something like this:
public class Test3 {
public static void main(String[] args) throws Exception {
String s2="text_t.txt";
File _newf = new File("text_d.txt");
changeOrder(_newf);
}
public static void changeOrder(File f) throws Exception {
FileInputStream _inp = new FileInputStream(f.getAbsolutePath());
BufferedReader _rd = new BufferedReader(new InputStreamReader(_inp));
ArrayList<String[]> newFileContent = new ArrayList<String[]>();
String _p=_rd.readLine();
while (_p != null) {
String [] _b = _p.split(" ");
String temp = _b[_b.length - 2];
_b[_b.length - 2] = _b[_b.length - 1];
_b[_b.length - 1] = temp;
newFileContent.add(_b);
_p=_rd.readLine();
}
PrintWriter writer = new PrintWriter(f.getAbsolutePath(), "UTF-8");
for (String[] line : newFileContent) {
for (String word : line) {
writer.print(word);
}
writer.println();
}
writer.close();
}
There is two minor changes:
First I changed the for loop you used in your code, with 3 lines of code.
Second I used to add all of lines which changed in the while loop in an ArrayList of String arrays which could hold changes in order to save on the file in the future.
And after all, I used an instance of PrintWriter class which could write a file on the hard disk. and in a foreach loop, I wrote contents of new file on the input file.

You could try something like this:
public static void changeOrder(File f) throws Exception {
FileInputStream _inp = new FileInputStream(f.getAbsolutePath());
BufferedReader _rd = new BufferedReader(new InputStreamReader(_inp));
String _p = _rd.readLine();
while (_p != null) {
String [] _b=_p.split(" ");
String temp = _b[_b.length - 1];
_b[_b.length - 1] = _b[_b.length - 2];
_b[_b.length - 2] = temp;
_p = _rd.readLine();
}
}
But if you want the file to be updated you need to write the results to the file...You should use something to write to the file like a PrintWriter.

This should do the trick You want:
public static String changeOrder(File fileName) throws IOException {
Scanner file = new Scanner(fileName);
String line = file.nextLine();
line = line.replace('.', ' ');
String[] items = line.split(" ");
StringBuilder sb = new StringBuilder();
sb.append(items[0] + " ");
sb.append(items[1] + " ");
sb.append(items[3] + " ");
sb.append(items[2] + ".");
return sb.toString();
}
Expected result: Student learns java programming.

Related

Is there a way to use a return value from a method in another method?

I am trying to use the return value fileName from the method file(), to the method nGram() so I can parse the contents of the file into n-grams. I have working code to do this but I want have two seperate methods.
package ie.gmit.sw;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
public class Example {
private String fileName;
private int k;
public Example(String fileName, int k) {
this.fileName = fileName;
this.k = k;
}
public String file(String fileName) throws IOException {
//Open the file.
FileReader fr = new FileReader(fileName);
Scanner inFile = new Scanner(fr);
// Read lines from the file till end of file
while (inFile.hasNext()) {
// Read the next line.
String line = inFile.nextLine();
// Display the line.
System.out.println(line);
}
// Close the file.
inFile.close();
return fileName;
}
private void nGram() throws IOException{
List<String> ngrams = new ArrayList<>();
for (int i = 0; i <= fileName.length() - k; i++) {
ngrams.add(fileName.substring(i, i + k));
}
System.out.println(ngrams);
}
//Working
// private static void run() throws FileNotFoundException {
// // Open the file.
// FileReader fr = new FileReader(fileName);
// Scanner inFile = new Scanner(fr);
//
// // Read lines from the file till end of file
// while (inFile.hasNext()) {
// // Read the next line.
// String line = inFile.nextLine();
// // Display the line.
// System.out.println(line);
//
// List<String> ngrams = new ArrayList<>();
// for (int i = 0; i <= line.length() - k; i++) {
// ngrams.add(line.substring(i, i + k));
// }
// System.out.println(ngrams);
// }
//
// // Close the file.
// inFile.close();
// }
public static void main(String[] args) throws Exception {
Scanner scanner = new Scanner(System.in);
System.out.println("Enter file: ");
String fileName = scanner.nextLine();
System.out.println("Enter kmers: ");
int k = scanner.nextInt();
scanner.close();
Example e = new Example(fileName, k);
e.file(fileName);
e.nGram();
}
}
Output
Hello world
Good Day okay
random text saying anything me laptop bye
[sa, am, mp, pl, le, e., .t, tx, xt]
To get the value returned from file(), you just need to pass a string in the nGram parameters, and call file(string) within it (because file() already returns a string).
private String file(String fileName){...}
private void nGram(String valueFromFile){...}
public static void main(String[] args) throws Exception {
...
Example e = new Example(fileName, k);
e.nGram(e.file(fileName));
}
Solution: Called the method nGram(line) in the method file().
package ie.gmit.sw;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
public class Example {
private String fileName;
private static int k;
public Example(String fileName, int k) {
this.fileName = fileName;
this.k = k;
}
public static String file(String fileName) throws IOException {
//Open the file.
FileReader fr = new FileReader(fileName);
Scanner inFile = new Scanner(fr);
// Read lines from the file till end of file
while (inFile.hasNext()) {
// Read the next line.
String line = inFile.nextLine();
// Display the line.
//System.out.println(line);
nGram(line);
}
// Close the file.
inFile.close();
return fileName;
}
private static void nGram(String j) throws IOException{
List<String> ngrams = new ArrayList<>();
for (int i = 0; i <= j.length() - k; i++) {
ngrams.add(j.substring(i, i + k));
}
System.out.println(ngrams);
}
//Working
// private static void run() throws FileNotFoundException {
// // Open the file.
// FileReader fr = new FileReader(fileName);
// Scanner inFile = new Scanner(fr);
//
// // Read lines from the file till end of file
// while (inFile.hasNext()) {
// // Read the next line.
// String line = inFile.nextLine();
// // Display the line.
// System.out.println(line);
//
// List<String> ngrams = new ArrayList<>();
// for (int i = 0; i <= line.length() - k; i++) {
// ngrams.add(line.substring(i, i + k));
// }
// System.out.println(ngrams);
// }
//
// // Close the file.
// inFile.close();
// }
public static void main(String[] args) throws Exception {
Scanner scanner = new Scanner(System.in);
System.out.println("Enter file: ");
String fileName = scanner.nextLine();
System.out.println("Enter kmers: ");
int k = scanner.nextInt();
scanner.close();
Example e = new Example(fileName, k);
file(fileName);
}
}

Printing a 2D array from the main method using exception handling

Hey so I've written some code to read the contents of a text file, do some comparisons and output either 1 or 0 into a 2D array. Here is a snippet
import java.io.*;
import java.util.*;
public class readFile
{
private String path;
//declare variables for visited and link
//String inputSearch1 = "Visited";
//String inputSearch2 = "Link";
String word;
public readFile(String pathname)
{
path = pathname;
}
//open the file and read it and search each line of the file for 'Visited' and 'Link'
public String[] OpenFile() throws IOException
{
FileReader fr = new FileReader(path);
BufferedReader lineReader = new BufferedReader(fr);
int numberOfLines = readLines();
String[] lineData = new String[numberOfLines];
int i;
for(i=0; i<numberOfLines; i++)
{
lineData[i] = lineReader.readLine();
}
lineReader.close();
return lineData;
}
//allows the file to be parsed without knowing the exact number of lines in it
int readLines() throws IOException
{
FileReader file_to_read = new FileReader(path);
BufferedReader bf = new BufferedReader(file_to_read);
String aLine;
int numberOfLines = 0;
while((aLine = bf.readLine()) != null)
{
numberOfLines++;
}
bf.close();
return numberOfLines;
}
int outLinks;
int inLinks;
String bLine;
String[] searchStrings() throws IOException
{
FileReader ftr = new FileReader(path);
BufferedReader bf2 = new BufferedReader(ftr);
int numberOfLines = readLines();
//String bLine;
String[] parseLine = new String[numberOfLines]; //array to store lines of text file
int[][] linkMatrix = new int[outLinks][inLinks]; //2d array to store the outLinks and inLinks
int i;
for(i=0; i<numberOfLines; i++)
{
parseLine[i] = bf2.readLine();
int j, k;
for(j=0; j<outLinks; j++)
{
for(k=0; k<inLinks;k++)
{
if(bLine.startsWith("Visited") && equals(bLine.startsWith("Link")))
{
linkMatrix[outLinks][inLinks] = 1;
}
else
{
linkMatrix[outLinks][inLinks] = 0;
}System.out.println(Arrays.deepToString(linkMatrix));
}//System.out.println();
}
}bf2.close();
return parseLine;
}
I am now trying to output this from the main method but each time I run it, all I get is the contents of the text file and no 2D matrix.
import java.io.IOException;
public class linkStatistics
{
public static void main(String[] args) throws IOException
{
// TODO Auto-generated method stub
//read file
String fileName = "C:\\Users\\Ikemesit\\Documents\\Lab_4.txt";
try
{
readFile file = new readFile(fileName);
//String[] lines = file.OpenFile();
String[] lines = file.searchStrings();
int i;
for(i=0;i<lines.length;i++)
{
System.out.println(lines[i]);
//System.out.println(lines2[i]);
}
}
catch(IOException e)
{
System.out.println(e.getMessage());
}
}
}
Any help would be much appreciated! Thanks.
This condition has many problems :
if(bLine.startsWith("Visited") && equals(bLine.startsWith("Link")))
You never initialize bLine. This means that the condition would throws NullPointerException. I'm assuming you want to test the lines you read from the file instead.
equals makes no sense in this context - it compares your readFile instance with a boolean.
A line can't start with both prefixes, so you probably want || (OR) instead of && (AND).
I think this would make more sense :
if(parseLine[i].startsWith("Visited") || parseLine[i].startsWith("Link"))

Array Required, but found Int

I'm running into an issue when converting some code for another project and was hoping for a bit of help. In the 'readFile' method, I am trying to parse a String to integers when I read the file. However, it is giving me the error 'array found, but int required'
import java.util.*;
import java.io.*;
public class JavaApplication1
{
static int [] matrix = new int [10];
static Scanner input = new Scanner(System.in);
public static void main(String[] args) throws IOException
{
String fileName = "Integers.txt";
// read the file
readFile(fileName);
// print the matrix
printArray(fileName, matrix);
}
// Read File
public static void readFile(String fileName) throws IOException
{
String line = "";
FileInputStream inputStream = new FileInputStream(fileName);
Scanner scanner = new Scanner(inputStream);
DataInputStream in = new DataInputStream(inputStream);
BufferedReader bf = new BufferedReader(new InputStreamReader(in));
int lineCount = 0;
String[] numbers;
while ((line = bf.readLine()) != null)
{
numbers = line.split(" ");
for (int i = 0; i < 10; i++)
{
matrix[lineCount][i] = Integer.parseInt(numbers[i]);
}
lineCount++;
}
bf.close();
}
public static void printToFile(String fileName, String output) throws IOException
{
java.io.File file = new java.io.File(fileName);
try (PrintWriter writer = new PrintWriter(file))
{
writer.print(output);
}
}
public static void printArray(String fileName, int [] array)
{
System.out.println("The matrix is:");
for (int i = 0; i < 10; i++)
{
System.out.println();
}
System.out.println();
}
}
matrix is an array of type int, which means matrix[lineCount] is an int.
You are tryng to do matrix[lineCount][i] which is getting the place i of an int.
That is why you are getting that error.
I guess you wanted matrix to be int[][] matrix = new int[10][10];
matrix[lineCount][i] = Integer.parseInt(numbers[i]);
is wrong.
Should be either
matrix[lineCount]= Integer.parseInt(numbers[i]);
OR
matrix[i]= Integer.parseInt(numbers[i]);

Find and replace a word in several text files with Java?

How can I find and replace a word in several text files, using Java?
Here's how I do it for a single String...
public class ReplaceAll {
public static void main(String[] args) {
String str = "We want replace replace word from this string";
str = str.replaceAll("replace", "Done");
System.out.println(str);
}
}
Using FileUtils from Commons IO:
String[] files = { "file1.txt", "file2.txt", "file3.txt" };
for (String file : files) {
File f = new File(file);
String content = FileUtils.readFileToString(new File("filename.txt"));
FileUtils.writeStringToFile(f, content.replaceAll("hello", "world"));
}
You can read in the file using a FileReader wrapped by a BufferedReader, pulling it in line by line, perform the same replace on the string that you show in your question, and write it back out to a new file.
This is the working code: Hope it helps!
import java.io.*;
import java.util.Scanner;
import java.util.StringTokenizer;
public class TestIO {
static StringBuilder sbword = new StringBuilder();
static String dirname = null;
static File[] filenames = null;
static Scanner sc = new Scanner(System.in);
public static void main(String args[]) throws FileNotFoundException, IOException{
boolean fileread = ReadFiles();
sbword = null;
System.exit(0);
}
private static boolean ReadFiles() throws FileNotFoundException, IOException{
System.out.println("Enter the location of folder:");
File file = new File(sc.nextLine());
filenames = file.listFiles();
String line = null;
for(File file1 : filenames ){
System.out.println("File name" + file1.toString());
sbword.setLength(0);
BufferedReader br = new BufferedReader(new FileReader(file1));
line = br.readLine();
while(line != null){
System.out.println(line);
sbword.append(line).append("\r\n");
line = br.readLine();
}
ReplaceLines();
WriteToFile(file1.toString());
}
return true;
}
private static void ReplaceLines(){
System.out.println("sbword contains :" + sbword.toString());
System.out.println("Enter the word to replace from each of the files:");
String from = sc.nextLine();
System.out.println("Enter the new word");
String To = sc.nextLine();
//StringBuilder sbword = new StringBuilder(stbuff);
ReplaceAll(sbword,from,To);
}
private static void ReplaceAll(StringBuilder builder, String from, String to){
int index = builder.indexOf(from);
while(index != -1){
builder.replace(index, index + from.length(), to);
index += to.length();
index = builder.indexOf(from,index);
}
}
private static void WriteToFile(String filename) throws IOException{
try{
File file1 = new File(filename);
BufferedWriter bufwriter = new BufferedWriter(new FileWriter(file1));
bufwriter.write(sbword.toString());
bufwriter.close();
}catch(Exception e){
System.out.println("Error occured while attempting to write to file: " + e.getMessage());
}
}
}

How to restore a text file?

I want to restore the following data from the text file. The problem is only one string/line I can restore, I can't restore the rest of the data.
Here's the code :
public static String restore(String filename) throws IOException, ClassNotFoundException
{
FileInputStream fn = new FileInputStream(filename);
ObjectInputStream ob = new ObjectInputStream(fn);
String sample = (String) ob.readObject();
return sample;
}
It is hard to understand the meaning of this question, but if you just want to read lines from a .txt file and into an array, then these two methods might help.
You just need to call String[] textArray = readFromFile("yourfilename.txt");
This gives you an array with each line in the file as an element.
Scanner fScan(String filename) {
Scanner sc = null;
try {
sc = new Scanner(new File(fname));
} catch (FileNotFoundException e) {
System.out.println("File not found:" + fname + " " + e);
}
return sc;
}
String[] readFromFile (String fname) {
Scanner sc = fScan(fname);
int length = 0;
String lineCounter;
while (sc.hasNext()){
lineCounter = sc.nextLine();
length++;
}
String[] array = new String[length];
sc = fScan(fname);
for (int i = 0; i < length; i++) {
array[i] = sc.nextLine();
}
sc.close();
return array;
}
Your code does only read the first Element within your binary file.
public static void restore(String filename) throws IOException, ClassNotFoundException
{
FileInputStream fn = new FileInputStream(filename);
ObjectInputStream ob = new ObjectInputStream(fn);
String string1 = (String) ob.readObject();
String string2 = (String) ob.readObject();
}
Are you sure you did not overwrite your file while serializing it?
But as far as I understand your Question you don't want to serialize/deserialize a String-Object, rather than reading/writing a textfile.
If you just want to read/write a file, you are on the wrong way with the ObjectInputStream.
ake a look at:
http://download.oracle.com/javase/1.3/docs/api/java/io/BufferedReader.html

Categories