How to read nextline of textfile in Java? - java

import java.io.*;
import java.util.*;
public class stringstore
{
public static void main(String[] args)
{
File file = new File("C:\\a.txt");
try
{
String strIP="";
Scanner sc = new Scanner(file);
while(sc.hasNext())
{
String line = sc.nextLine();
String str[] = line.split(", ");
strIP = str[0];
}
System.out.println(strIP);
}
catch(IOException e)
{
// work with the errors here
}
}
}
How do I read a nextline from a textfile and display it.

There is only slight mistake in your code.
Try this.
import java.io.*;
import java.util.*;
public class stringstore
{
public static void main(String[] args)
{
File file = new File("C:\\a.txt");
try
{
String strIP="";
Scanner sc = new Scanner(file);
while(sc.hasNext())
{
String line = sc.nextLine();
String str[] = line.split(", ");
strIP = str[0];
System.out.println(strIP);
}
}
catch(IOException e)
{
// work with the errors here
}
}
}
place the print statement inside the loop

You can read file line by line:
BufferedReader bufferedReader = new BufferedReader(new FileReader(new File("filename")));
String line = null;
while ((line = bufferedReader.readLine()) != null) {
System.out.println(line);
}

Related

Create a new ArrayList based on input files, and print the first word of each element

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

How to print text file left to right, and then upside down?

My goal for this program is to read a text file, print it normally, then print it flipped from left to right, and then flipped upside down. I can print the original, however I'm unsure of how to read the file so it will print in the other two formats, and how to print in these formats. I can only import the file once.
Here is an example output, if my description is inadequate.
The code as it is now:
import java.io.*;
import java.util.*;
public class Problem2
{
public static void main(String[] args) throws IOException
{
File marge = new File("marge.txt");
Scanner fileScan = new Scanner(marge);
String original;
while (fileScan.hasNext())
{
original = fileScan.nextLine();
System.out.println(original);
}
String lefttoright;
while (fileScan.hasNext())
{
lefttoright = fileScan.nextLine();
System.out.println(lefttoright);
}
String upsidedown;
while (fileScan.hasNext())
{
upsidedown = fileScan.nextLine();
System.out.println(upsidedown);
}
fileScan.close();
}
}
Try to use StringBuilder(element).reverse().toString(); where element is a string.
Example of working code:
package test;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public class test {
public static void main(String[] args) throws IOException {
// TODO Auto-generated method stub
File file = new File("C:\\Users\\xxx\\Documents\\test.txt");
List<String> listString = new ArrayList<>();
BufferedReader br = new BufferedReader(new FileReader(file));
String line;
//write as is
while ((line = br.readLine()) != null) {
System.out.println(line);
}
System.out.println("");
br = new BufferedReader(new FileReader(file));
//write in reverse
while ((line = br.readLine()) != null) {
String result = new StringBuilder(line).reverse().toString();
System.out.println(result);
}
System.out.println("");
br = new BufferedReader(new FileReader(file));
while ((line = br.readLine()) != null) {
listString.add(line);
}
//write down up
Collections.reverse(listString);
for (String element : listString) {
String result = new StringBuilder(element).reverse().toString();
System.out.println(result);
}
}
}
Test example:
test.txt file content:
alpha
tree
123
Output:
alpha
tree
123
ahpla
eert
321
321
eert
ahpla
You might consider as below. this will save you the hassle with reading 3 times from the file.
import java.io.*;
import java.util.*;
public class Problem2 {
public static void main(String[] args) throws IOException {
File marge = new File("marge.txt");
Scanner fileScan = new Scanner(marge);
String original;
while (fileScan.hasNext()) {
original = fileScan.nextLine();
System.out.println(original);
}
System.out.println(original);
System.out.println();
System.out.print(flip(original));
System.out.println();
System.out.print(updsideDown(original));
}
public static String flip(String input) {
StringBuffer output = new StringBuffer();
String[] intermInput = input.split("\n");
for (int i = 0; i < intermInput.length; i++) {
StringBuffer strBuff = new StringBuffer(intermInput[i]);
output.append(strBuff.reverse());
output.append("\n");
}
output.substring(0, output.length());
return output.toString();
}
public static String updsideDown(String input) {
StringBuffer output = new StringBuffer();
String[] intermInput = input.split("\n");
for (int i = intermInput.length - 1; i >= 0; i--) {
output.append(intermInput[i]);
output.append("\n");
}
output.substring(0, output.length());
return output.toString();
}
}
Either use suggestion from YCF_L or use below solution.
import java.io.*;
import java.util.*;
public class Problem2 {
public static void main(String[] args) throws IOException {
File marge = new File("marge.txt");
Scanner fileScan = new Scanner(marge);
String original;
while (fileScan.hasNext()) {
original = fileScan.nextLine();
System.out.println(original);
}
fileScan = new Scanner(marge);
String lefttoright;
while (fileScan.hasNext()) {
lefttoright = fileScan.nextLine();
StringBuffer sb = new StringBuffer(lefttoright);
System.out.println(sb.reverse());
}
fileScan = new Scanner(marge);
String upsidedown;
Stack<String> list = new Stack<String>();
while (fileScan.hasNext()) {
upsidedown = fileScan.nextLine();
list.push(upsidedown);
}
for (int i = 0; i <= list.size(); i++) {
System.out.println(list.pop());
}
fileScan.close();
}
}

How do you input a line into a array separated as array elements?(Java)

Using a scanner to read a line of input. I thought there was a way to directly insert the line into an array and have it separate into string elements (divided by spaces).
import java.util.Scanner;
public class Main
{
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
int numberOfStudents = input.nextInt();
input.nextLine();
String[][] partners = new String[2][numberOfStudents];
partners[1] = input.nextLine();
}
}
I attempted to rewrite your code to possibly be what you want. Could you try to specify exactly what you're trying to do?
import java.util.Scanner;
public class Main
{
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
int numberOfStudents = input.nextInt();
//input.nextLine();
String[][] partners = new String[2][numberOfStudents];
for(int i=0; i<numberOfStudents; i++)
{
partners[1][i] = input.nextLine();
}
}
}
I think you're looking for split.
For example:
String val="I am a String";
String [] tabDelimitedVals=val.split(" ");
This is seen in the stack overflow post here:
How to split a string in Java
To read from a file, you can use
BufferedReader br = new BufferedReader(new FileReader("file.txt"));
try {
StringBuilder sb = new StringBuilder();
String line = br.readLine();
while (line != null) {
sb.append(line);
sb.append(System.lineSeparator());
line = br.readLine();
}
String everything = sb.toString();
} finally {
br.close();
}
The above was taken from: Reading a plain text file in Java
Together, you can do:
BufferedReader br = new BufferedReader(new FileReader("file.txt"));
try {
String val=br.readLine();
String [] splitted=val.split(" ");
}
finally {
br.close();
}

Java exception from scanning a file that was imported

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 */
}
}

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());
}
}
}

Categories