How can I read a file into a array of String[] and then convert it into ArrayList?
I can't use an ArrayList right away because my type of list is not applicable for the arguments (String).
So my prof told me to put it into an array of String, then convert it.
I am stumped and cannot figure it out for the life of me as I am still very new to java.
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
/**
* Created by tsenyurt on 06/04/15.
*/
public class ReadFile
{
public static void main(String[] args) {
List<String> strings = new ArrayList<>();
BufferedReader br = null;
try {
String sCurrentLine;
br = new BufferedReader(new FileReader("/Users/tsenyurt/Development/Projects/java/test/pom.xml"));
while ((sCurrentLine = br.readLine()) != null) {
System.out.println(sCurrentLine);
strings.add(sCurrentLine);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (br != null)br.close();
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
}
there is a code that reads a file and create a ArrayList from it
http://www.mkyong.com/java/how-to-read-file-from-java-bufferedreader-example/
Well there are many ways to do that,
you can use this code if you want have a List of each word exist in your file
public static void main(String[] args) {
BufferedReader br = null;
StringBuffer sb = new StringBuffer();
List<String> list = new ArrayList<>();
try {
String sCurrentLine;
br = new BufferedReader(new FileReader(
"Your file path"));
while ((sCurrentLine = br.readLine()) != null) {
sb.append(sCurrentLine);
}
String[] words = sb.toString().split("\\s");
list = Arrays.asList(words);
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (br != null)
br.close();
} catch (IOException ex) {
ex.printStackTrace();
}
}
for (String string : list) {
System.out.println(string);
}
}
Related
I have a Java program that troubleshoots common problems with phones. To do this I have set up a scanner that reads the user input for any keywords. If one of these keywords is found, a method will output from a text file a solution to the problem suggested by that keyword.
My problem is that when I run the program, all the lines from the text file are outputted, from every method, disregarding my input.
Here's the code:
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.Scanner;
public class task2 {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.println("What is your problem?");
String input = scan.nextLine();
String[] problems = {"screen", "display", "broken", "cracked", "camera", "flash", "ports"};
String[] solutions = input.split("broken");
for(int x=0; x < problems.length; x++){
if(input.contains("broken")){
if(input.contains("screen")){
brokenScreen();
} else{
}
if(input.contains("display")) {
brokenDisplay();
} else{
}
if(input.contains("camera")) {
brokenCamera();
} else{
}
if(input.contains("flash")) {
brokenFlash();
} else{
}
if(input.contains("ports")) {
brokenPorts();
} else{
}
}
else{
}
if(input.contains("cracked")) {
if(input.contains("screen")) {
crackedScreen();
} else{
}
}
if(input.contains("water")) {
waterPhone();
}
else{
}
}
brokenScreen();
brokenDisplay();
crackedScreen();
brokenCamera();
brokenFlash();
brokenPorts();
waterPhone();
noSolution();
}
public static void noSolution() {
String file = "C:/Users/Nicholas Gawley/workspace/Second Practice Controlled Assessment/src/solutions.txt"; //Location of the text file
try {
FileReader filereader = new FileReader(file);
BufferedReader bufferedreader = new BufferedReader(filereader);
while((file = bufferedreader.readLine()) != null){
System.out.println(file);
}
bufferedreader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
public static void waterPhone() {
String file = "C:/Users/Nicholas Gawley/workspace/Second Practice Controlled Assessment/src/solutions.txt"; try {
FileReader filereader = new FileReader(file);
BufferedReader bufferedreader = new BufferedReader(filereader);
while((file = bufferedreader.readLine()) != null){
System.out.println(file);
}
bufferedreader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
public static void brokenPorts() {
String file = "C:/Users/Nicholas Gawley/workspace/Second Practice Controlled Assessment/src/solutions.txt"; try {
FileReader filereader = new FileReader(file);
BufferedReader bufferedreader = new BufferedReader(filereader);
while((file = bufferedreader.readLine()) != null){
System.out.println(file);
}
bufferedreader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
public static void brokenFlash() {
String file = "C:/Users/Nicholas Gawley/workspace/Second Practice Controlled Assessment/src/solutions.txt"; try {
FileReader filereader = new FileReader(file);
BufferedReader bufferedreader = new BufferedReader(filereader);
while((file = bufferedreader.readLine()) != null){
System.out.println(file);
}
bufferedreader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
public static void brokenCamera() {
String file = "C:/Users/Nicholas Gawley/workspace/Second Practice Controlled Assessment/src/solutions.txt"; try {
FileReader filereader = new FileReader(file);
BufferedReader bufferedreader = new BufferedReader(filereader);
while((file = bufferedreader.readLine()) != null){
System.out.println(file);
}
bufferedreader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
public static void crackedScreen() {
String file = "C:/Users/Nicholas Gawley/workspace/Second Practice Controlled Assessment/src/solutions.txt"; try {
FileReader filereader = new FileReader(file);
BufferedReader bufferedreader = new BufferedReader(filereader);
while((file = bufferedreader.readLine()) != null){
System.out.println(file);
}
bufferedreader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
public static void brokenDisplay() {
String file = "C:/Users/Nicholas Gawley/workspace/Second Practice Controlled Assessment/src/solutions.txt"; try {
FileReader filereader = new FileReader(file);
BufferedReader bufferedreader = new BufferedReader(filereader);
while((file = bufferedreader.readLine()) != null){
System.out.println(file);
}
bufferedreader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
public static void brokenScreen() {
String file = "C:/Users/Nicholas Gawley/workspace/Second Practice Controlled Assessment/src/solutions.txt"; try {
FileReader filereader = new FileReader(file);
BufferedReader bufferedreader = new BufferedReader(filereader);
while((file = bufferedreader.readLine()) != null){
System.out.println(file);
}
bufferedreader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
Can anyone please solve this issue? Any help would be greatly appreciated.
Remove
brokenScreen();
brokenDisplay();
crackedScreen();
brokenCamera();
brokenFlash();
brokenPorts();
waterPhone();
noSolution();
at the end of your main method (after the for loop).
I want to read the DNA text file of bacteria using java i made this
code
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
// implements a simplified version of "type" command provided in Windows given
// a text file name(s) as argument, it prints the content of the text file(s) on console
class Type {
public static void main(String[] args) {
BufferedReader br = null;
try {
String sCurrentLine;
br = new BufferedReader(new FileReader("C:\\Users\\mohamed\\Downloads\\dataset_2_6.txt"));
while ((sCurrentLine = br.readLine()) != null) {
System.out.println(sCurrentLine);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (br != null)br.close();
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
}
but the output is null
, it work when using small text file
I'm trying to introduce a line break at every 100th character of the line from the existing file.But it doesn't write anything to it. below is the code written in java to read the existing file and write to it with a temporary file.
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
public class ReplaceFileContents {
public static void main(String[] args) {
new ReplaceFileContents().replace();
}
public void replace() {
String oldFileName = "Changed1.ldif";
String tmpFileName = "Changed2.ldif";
BufferedReader br = null;
BufferedWriter bw = null;
try {
br = new BufferedReader(new FileReader(oldFileName));
bw = new BufferedWriter(new FileWriter(tmpFileName));
String line;
while ((line = br.readLine()) != null) {
line.replaceAll("(.{100})", "$1\n");
}
} catch (Exception e) {
return;
} finally {
try {
if(br != null)
br.close();
} catch (IOException e) {
//
}
try {
if(bw != null)
bw.close();
} catch (IOException e) {
//
}
}
// Once everything is complete, delete old file..
File oldFile = new File(oldFileName);
oldFile.delete();
// And rename tmp file's name to old file name
File newFile = new File(tmpFileName);
newFile.renameTo(oldFile);
}
}
while ((line = br.readLine()) != null) {
line.replaceAll("(.{100})", "$1\n");
}
First off, line.replaceAll does not replace your line variable with the result. Because Strings are immutable, this method returns the new string, so your line should be line = line.replaceAll(....
Second, you're never writing the new String back into the file. Using replaceAll doesn't change the file itself in any way. Instead, try using your bw object to write the new String to the same line.
From what you've published here, you never try to write line back to bw. Try this:
package hello;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
public class Test {
public static void main(String[] args) {
new Test().replace();
}
public void replace() {
String oldFileName = "d:\\1.txt";
String tmpFileName = "d:\\2.txt";
BufferedReader br = null;
BufferedWriter bw = null;
try {
br = new BufferedReader(new FileReader(oldFileName));
bw = new BufferedWriter(new FileWriter(tmpFileName));
String line;
while ((line = br.readLine()) != null) {
line = line.replaceAll("(.{100})", "$1\n");
bw.write(line);
}
} catch (Exception e) {
return;
} finally {
try {
if(br != null)
br.close();
} catch (IOException e) {
//
}
try {
if(bw != null)
bw.close();
} catch (IOException e) {
//
}
}
// Once everything is complete, delete old file..
File oldFile = new File(oldFileName);
oldFile.delete();
// And rename tmp file's name to old file name
File newFile = new File(tmpFileName);
newFile.renameTo(oldFile);
}
}
You never try to write line back to bw;
String#replaceAll will return the copy of the source not the original String;
In my below code I wanted to replace the text "DEMO" with "Demographics" but instead of replacing the text it deletes the entire content of the text file.
Contents inside the file:
DEMO
data
morning
PS: I'm a beginner in java
package com.replace.main;
import java.io.*;
public class FileEdit {
public static void main(String[] args) {
BufferedReader br = null;
BufferedWriter bw = null;
String readLine, replacedData;
try {
bw = new BufferedWriter(
new FileWriter(
"Demg.ctl"));
br = new BufferedReader(
new FileReader(
"Demg.ctl"));
System.out.println(br.readLine()); //I Get Null Printed Here
while ((readLine = br.readLine())!= null) {
System.out.println("Inside While Loop");
System.out.println(readLine);
if (readLine.equals("DEMO")) {
System.out.println("Inside if loop");
replacedData = readLine.replaceAll("DEMO","Demographics");
}
}
System.out.println("After While");
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
You open a Writer to your file, but you don't write anything. This means that your file is replaced with an empty file.
Besides this you also need to close your writer, not just the reader.
And last but not least, your if condition is wrong.
if (readLine.equals("DEMO")) {
should read
if (readLine.contains("DEMO")) {
Otherwise it would only return true if your line contained "DEMO" but nothing else.
I'm updating the answer to my own question.
package com.replace.main;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
public class FileEdit
{
public static void main(String args[])
{
try
{
BufferedReader reader = new BufferedReader(new FileReader("Demg.ctl"));
String readLine = "";
String oldtext = "";
while((readLine = reader.readLine()) != null)
{
oldtext += readLine + "\r\n";
}
reader.close();
// To replace the text
String newtext = oldtext.replaceAll("DEMO", "Demographics");
FileWriter writer = new FileWriter("Demg.ctl");
writer.write(newtext);
writer.close();
}
catch (IOException e)
{
e.printStackTrace();
}
}
}
I am trying to do the following: I am making a program in Java which let me create and read text files. So far I have been able to do this, but the hard(?) part is this: I have to be able to get an error when anything else but A, B or C is inside the text file.
So far I got:
package textfile;
import java.io.*;
import static java.lang.System.*;
class OutWrite {
public static void main(String[] args) {
try{
FileWriter fw = new FileWriter("FAS.txt");
PrintWriter pw = new PrintWriter(fw);
pw.println("A");
pw.println("B");
pw.println("C");
pw.close();
} catch (IOException e){
out.println("ERROR!");
}
}
}
And
package textfile;
import java.io.*;
import static java.lang.System.*;
class InRead {
public static void main(String[] args) {
try {
FileReader fr = new FileReader("FSA.txt");
BufferedReader br = new BufferedReader(fr);
String str;
while ((str = br.readLine()) != null){
out.println(str);
}
br.close();
} catch (IOException e) {
out.println("File not found");
}
}
}
Can anyone steer me in the right direction, please?
Just throw Exception when a new Character is found other than A,B,C .
use,
class InRead {
public static void main(String[] args) {
try {
FileReader fr = new FileReader("FSA.txt");
BufferedReader br = new BufferedReader(fr);
String str;
while ((str = br.readLine()) != null) {
if (str.equals("A") || str.equals("B") || str.equals("c")) //compare
out.println(str);
else
throw new Exception(); //throw exception
}
br.close();
} catch (IOException e) {
out.println("File not found");
}
catch (Exception e) {//catch it here and print the req message
System.out.println("New Character Found");
}
}
}