I am having a bit of an issues trying to pass in a file read by my program and sorted accordantly. I am not used to working with files, and i ran out of ideas as to how this could be achieved.
/////////////////////////////////////// class reads file ///////////////////////////////////
import java.io.*;
public class InFileReader {
private BufferedReader inputStream = null;
private String fileLine;
private StringBuilder sb;
public String getFile(File fileRead) throws FileNotFoundException,
IOException {
inputStream = new BufferedReader(new FileReader(fileRead)); //reads files
sb = new StringBuilder();
while((fileLine = inputStream.readLine()) != null){//keep reading lines in file till there is none
sb.append(fileLine).append("\n");
}
return sb.toString(); //returns StringBuffer read values in String form
}
}
///////////////////////////////////////////////////// end of read file class ///////////////////////
public void getFile(File fileRead) throws FileNotFoundException,
IOException {
try {
String input = fileReader.getFile(fileRead.getAbsoluteFile());
HashMap<Integer, Thing.Ship> hashmap = new HashMap<>();
while (!input.isEmpty()) { // as long as there is data in the file keep looping
Scanner sc = new Scanner(input); // scan file
if (!input.startsWith("//")) { // take out "//" from directory
String type = "";
if (sc.hasNext()) { // if there are character lines get next line
type = sc.next();
}
if (type.equalsIgnoreCase("port")) { // looks for "port"
world.assignPort(new Thing.SeaPort(sc)); // assigns value to Seaport
} else if (type.equalsIgnoreCase("dock")) {
world.assignDock(new Thing.Dock(sc));
} else if (type.equalsIgnoreCase("ship")) {
Thing.Ship s = new Thing.Ship(sc);
hashmap.put(s.getIndex(), s);
world.assignShip(s);
} else if (type.equalsIgnoreCase("pship")) {
Thing.Ship s = new Thing.PassengerShip(sc);
hashmap.put(s.getIndex(), s);
world.assignShip(s);
} else if (type.equalsIgnoreCase("cship")) {
Thing.Ship s = new Thing.CargoShip(sc);
hashmap.put(s.getIndex(), s);
world.assignShip(s);
} else if (type.equalsIgnoreCase("person")) {
world.assignPerson(new Thing.Person(sc));
}
}
}
//inputOut.setText(type);
inputOut.setText(world.toString());
} catch (Exception e) {
System.out.println(e + "-----");
}
}
Here fileRead knows where to find the file to be read "C:\Users\abe\IdeaProjects\CreateSeaPortDataFile\src\text.txt"
public void getFile(File fileRead) throws FileNotFoundException,
IOException {
this is where things just fall apart:
String input = fileReader.getFile(fileRead.getAbsoluteFile());
My intent here is to pass the location of the file so that the getFile class can read it and then be sorted into the hashmap.
again i am not familiar with how to work with file, any suggestion or comment would be greatly appreciated.
thank you in advanced.
If you get a FileNotFoundException then the file was not found.
You say the filename was "C:\Users\abe\IdeaProjects\CreateSeaPortDataFile\src\text.txt".
If you type that name in the code you must escape the backslash:
"C:\\Users\\abe\\IdeaProjects\\CreateSeaPortDataFile\\src\\text.txt".
Related
I am attempting to use the method "public boolean readArtists" with a scanner to read strings from a file and return true if opened successfully. This method is also supposed to "Adds to the list all of the artists stored in the file passed parameter."
I've seen how to write the code in a public static void method that will read the text file and return it:
public static void main(String[] args) {
File file = new File("artists30.txt");
String content = null;
try {
try (Scanner scanner = new Scanner(file, StandardCharsets.UTF_8.name())) {
content = scanner.useDelimiter("\\A").next();
}
} catch (IOException e) {
e.printStackTrace();
}
System.out.println(content);
}
Here is the test:
I have to keep the method "public boolean readArtists(String filename), so my question is, within this method, how do I read the contents of the text file into an ArrayList using a scanner, while also returning true if the file is opened successfully, Otherwise, handling the exception, displaying an appropriate error message containing the name of the missing file and return false.
public class Artists{
public static ArrayList<String> artists = new ArrayList<String>();
public static void main(String[] args) {
System.out.println(readArtists("filename goes here"));
System.out.println(artists);
}
public Artists(String artist, String genre)
{
}
public static boolean readArtists(String fileName) {
Scanner sc = null;
try {
File file = new File(fileName);
if(file.createNewFile()) {
System.out.println("err "+fileName);
return false;
}
sc = new Scanner(file);
while(sc.hasNextLine()) {
artists.add(sc.nextLine());
}
}catch(Exception e) {
e.printStackTrace();
}
if(sc!=null) {sc.close();}
return true;
}
}
This answer reads data from a .txt document into an ArrayList, as long as the .txt document names are on seperate lines in the document. It also outputs err \FILE\NAME and returns false if the document does not exist and true if it does. https://www.w3schools.com/java/java_files.asp is a great website to learn java by the way and this link brings you to the file handling page.
You can achieve that using,
public static void main(String[] args) throws FileNotFoundException {
String filepath = "C:\\Users\\Admin\\Downloads\\testFile.txt";
List<String> arrayList = new ArrayList<>();
if(readArtists(filepath)) {
Scanner sc = new Scanner(new File(filepath));
sc.useDelimiter("\\A");
while(sc.hasNext()) {
arrayList.add(sc.next());
}
}
System.out.println(arrayList);
}
public static boolean readArtists(String filename)
{
File file = new File(filename); //full path of the file with name
return file.canRead();
}
I have been trying to compare the file content with user input. The program is reading from a specific file and it checks against the user's string input. I am having trouble comparing the ArrayList with the user input.
public class btnLoginListener implements Listener
{
#Override
public void handleEvent(Event arg0)
{
//variables for the class
username = txtUsername.getText();
password = txtPassword.getText();
MessageBox messageBox = new MessageBox(shell, SWT.OK);
try {
writeFile();
messageBox.setMessage("Success Writing the File!");
} catch (IOException x)
{
messageBox.setMessage("Something bad happened when writing the file!");
}
try {
readFile("in.txt");
} catch (IOException x)
{
messageBox.setMessage("Something bad happened when reading the file!" + x);
}
if (username.equals(names))
{
messageBox.setMessage("Correct");
}
else
{
messageBox.setMessage("Wrong");
}
messageBox.open();
}
}
private static void readFile(String fileName) throws IOException
{
//use . to get current directory
File dir = new File(".");
File fin = new File(dir.getCanonicalPath() + File.separator + fileName);
// Construct BufferedReader from FileReader
BufferedReader br = new BufferedReader(new FileReader(fin));
String line = null;
while ((line = br.readLine()) != null)
{
Collections.addAll(names, line);
}
br.close();
}
I am assuming you are trying to check whether an element exists in the list. If yes, then you need to use contains method, here's the Javadoc.
So, instead of using if (username.equals(names)), you can use if (names.contains(username)).
Apart from this, you should make the following changes:
Don't read the file every time an event is called. As you are reading a static file, you can read it once and store it in an ArrayList.
Make variables username and password local.
Remove writeFile() call unless it's appending/writing dynamic values on each event.
Hi I have Text file having some tag based data and i want to split into multiple text files.
Main Text files having data like this:
==========110CYL067.txt============
<Entity Text>Cornell<Entity Type>Person
<Entity Text>Donna<Entity Type>Person
<Entity Text>Sherry<Entity Type>Person
<Entity Text>Goodwill<Entity Type>Organization
==========110CYL068.txt============
<Entity Text>Goodwill Industries Foundation<Entity Type>Organization
<Entity Text>Goodwill<Entity Type>Organization
NOTE: Over here 110CYL068.txt and 110CYL067.txt are text files.
I want to split this file into 110CYL068.txt and 110CYL067.txt and so on.
This ============ pattern is fixed.Between ============ FileName ============
file name could be anything.does anyone have any insight.
I don't want to write codes for you, so you can read the file using a BufferedReader or FileReader. You can create and write to a new File using any file writer whenever you see a line starting with ======= or containing .txt.
If you encounter those close the previous file and repeat the process.
Done ppl way to complicatet just did it fast and dirty.
public static List<String> lines = new ArrayList<String>();
public static String pattern = "==========";
public static void main(String[] args) throws IOException {
addLines(importFile());
}
private static List<String> importFile() throws FileNotFoundException, IOException {
BufferedReader br = new BufferedReader(new FileReader("C:\\temp\\test.txt"));
try {
StringBuilder sb = new StringBuilder();
String line = br.readLine();
while (line != null) {
lines.add(line.replaceFirst(pattern, ";") + "\n");
line = br.readLine();
}
} finally {
br.close();
}
return lines;
}
private static void addLines(List<String> list) throws IOException {
String FilesString = list.toString();
System.out.println(FilesString);
String[] FilesArray = FilesString.split(";");
for (String string : FilesArray) {
createFile(string);
}
}
private static void createFile(String content) throws IOException {
String[] Lines = content.replaceAll("=", "").split("\n");
File file = new File("C:\\temp\\" + Lines[0]);
file.createNewFile();
FileWriter writer = new FileWriter(file);
Lines[0] = null;
for (String Line : Lines) {
if (Line != null) {
writer.append(Line.replace(",", "")+"\n");
}
}
writer.flush();
writer.close();
}
}
Also quick and dirty, not using regex. I don't really recommend doing it like this because the for loop in main is quite confusing and could break, but it might be beneficial to use this for ideas.
import java.io.*;
import java.util.*;
class splitFiles {
public static void main(String[] args){
try {
List<String> fileRead = readFiles("some.txt");
for(int i=0; i<fileRead.size(); i++){
if(fileRead.get(i).charAt(0) == '='){
PrintWriter writer = new PrintWriter(getFileName(fileRead.get(i)), "UTF-8");
for(int j=i+1; j<fileRead.size(); j++){
if(fileRead.get(j).charAt(0) == '='){
break;
} else {
writer.println(fileRead.get(j));
}
}
writer.close();
}
}
} catch (Exception e){
}
}
public static String getFileName(String fileLine){
String[] split = fileLine.split("=");
for(String e: split){
if(e.isEmpty()){
continue;
} else {
return e;
}
}
return "No file name found";
}
public static ArrayList<String> readFile(String path){
try {
Scanner s = new Scanner(new File(path));
ArrayList<String> list = new ArrayList<String>();
while(s.hasNext()){
list.add(s.next());
}
s.close();
return list;
} catch (FileNotFoundException f){
System.out.println("File not found.");
}
return null;
}
static List<String> readFiles(String fileName) throws IOException {
List<String> words = new ArrayList<String>();
BufferedReader reader = new BufferedReader(new FileReader(fileName));
String line;
while ((line = reader.readLine()) != null) {
words.add(line);
}
reader.close();
return words;
}
}
For a testing course assignment, I need to create unit tests for my already-coded system using JUnit. My system is heavily dependent on each other and it also writes/reads from a couple of text files on my disk.
I realize I have to eliminate all dependancies to successfully unit test, I just don't know how to create stubs for Files.
Any help in code, tools or concepts is welcome
import Objs.*;
import java.io.*;
import java.net.URL;
import java.util.Scanner;
/**
*This class communicates with the users file by writing to it, reading from it, searching, deleting...
*
*/
public class users {
public static File usersFile = new File("usersFile.txt");
public static PrintWriter writer;
static Scanner read ;
public static void write(userObj u){
try {
String gather = read();
String newUser = u.toString();
writer = new PrintWriter(usersFile);
writer.append(gather).append(newUser).append("\n");
writer.close();
System.out.println("The users' file has been updated");
}
catch(FileNotFoundException ex){
System.out.print("file not found");
}
}
public static String read(){
String f = null;
try {
read = new Scanner(usersFile);
StringBuilder gather = new StringBuilder();
while(read.hasNext()){
gather.append(read.nextLine()).append("\n");
}
f = gather.toString();
}
catch(FileNotFoundException ex){
System.out.print("file not found");
}
return f;
}
public static userObj search(String s){
userObj foundUser = null;
try {
read = new Scanner(usersFile);
String st=null;
while(read.hasNext()){
if (read.next().equalsIgnoreCase(s)){
foundUser = new userObj();
foundUser.name = s;
foundUser.setType(read.next().charAt(0));
foundUser.credit = read.nextDouble();
}
}
}
catch(FileNotFoundException ex){
System.out.print("file not found");
}
return foundUser;
}
public static void remove(userObj u){
String s = u.name;
if (search(s) == null){
return;}
try {
read = new Scanner(usersFile);
StringBuilder gather = new StringBuilder();
while(read.hasNext()){
String info = read.nextLine();
if (info.startsWith(s)){
continue;
}
gather.append(info).append("\n");
}
writer = new PrintWriter(usersFile);
writer.append(gather).append("\n");
writer.close();
System.out.println("The user has been deleted");
}
catch(FileNotFoundException ex){
System.out.print("file not found");
}}
public static void update(userObj u){
remove(u);
write(u);
}
}
You don't need to create "stubs for files", you need to create "stub for reading from an InputStream".
For read, search, and remove you're using Scanner, which accepts an InputStream as one of its overloaded constructors. If you add an InputStream parameter, you can use that to construct your Scanner. With normal use, you can pass a FileInputStream, while using a StringBufferInputStream for testing.
For write and remove you're using a PrintWriter, which accepts an OutputStream as one of its overloaded constructors. If you add an OutputStream parameter, you can use that to construct your PrintWriter. With normal use, you can pass a FileOutputStream, while using a ByteArrayOutputStream for testing. If you want to read the result as a string from your test, use toString(String charsetName).
public class Users {
...
public static void write(UserObj u, InputStream input, OutputStream output) {
...
String gather = read(input);
...
writer = new PrintWriter(output);
...
}
public static String read(InputStream input) {
...
read = new Scanner(input);
...
}
public static UserObj search(String s, InputStream input) {
...
read = new Scanner(input);
...
}
public static void remove(UserObj u, InputStream input, OutputStream output) {
...
read = new Scanner(input);
...
writer = new PrintWriter(output);
...
}
public static void update(UserObj u, InputStream input, OutputStream output) {
remove(u, input, output);
write(u, input, output);
}
}
// Client code example
FileInputStream input = new FileInputStream("usersFile.txt");
FileOutputStream output = new FileOutputStream("usersFile.txt");
...
Users.write(myUser, input, output);
...
String result = Users.read(input);
...
myUser = Users.search(myString, input);
...
Users.remove(myUser, input, output);
...
Users.update(myUser, input, output);
// Testing code example
StringBufferInputStream input = new StringBufferInputStream("...");
ByteArrayOutputStream output = new ByteArrayOutputStream();
...
Users.write(myUser, input, output);
...
String result = Users.read(input);
...
myUser = Users.search(myString, input);
...
Users.remove(myUser, input, output);
...
Users.update(myUser, input, output);
...
result = output.toString("UTF-8"); // see docs for other legal charset names
I have 4 different files in some locations like:
D:\1.txt
D:\2.txt
D:\3.txt and
D:\4.txt
I need to create a new file as NewFile.txt, It should contains all the contents present in the above files 1.txt, 2.txt,3.txt 4.txt.......
All Data should present in the New Single file(NewFile.txt)..
Please suggest me some idea to do the same in java or Groovy....
Here's one way to do it in Groovy:
// Get a writer to your new file
new File( '/tmp/newfile.txt' ).withWriter { w ->
// For each input file path
['/tmp/1.txt', '/tmp/2.txt', '/tmp/3.txt'].each { f ->
// Get a reader for the input file
new File( f ).withReader { r ->
// And write data from the input into the output
w << r << '\n'
}
}
}
The advantage of doing it this way (over calling getText on each of the source files) is that it will not need to load the entire file into memory before writing its contents out to newfile. If one of your files was immense, the other method could fail.
This is in groovy
def allContentFile = new File("D:/NewFile.txt")
def fileLocations = ['D:/1.txt' , 'D:/2.txt' , 'D:/3.txt' , 'D:/4.txt']
fileLocations.each{ allContentFile.append(new File(it).getText()) }
i am showing you the way it is to be done in java:
public class Readdfiles {
public static void main(String args[]) throws Exception
{
String []filename={"C:\\WORK_Saurabh\\1.txt","C:\\WORK_Saurabh\\2.txt"};
File file=new File("C:\\WORK_Saurabh\\new.txt");
FileWriter output=new FileWriter(file);
try
{
for(int i=0;i<filename.length;i++)
{
BufferedReader objBufferedReader = new BufferedReader(new FileReader(getDictionaryFilePath(filename[i])));
String line;
while ((line = objBufferedReader.readLine())!=null )
{
line=line.replace(" ","");
output.write(line);
}
objBufferedReader.close();
}
output.close();
}
catch (Exception e)
{
throw new Exception (e);
}
}
public static String getDictionaryFilePath(String filename) throws Exception
{
String dictionaryFolderPath = null;
File configFolder = new File(filename);
try
{
dictionaryFolderPath = configFolder.getAbsolutePath();
}
catch (Exception e)
{
throw new Exception (e);
}
return dictionaryFolderPath;
}
}
tell me if you have any doubts
I tried solving this and i found its quite easy if you copy the contents to an array and write the array to a different file
public class Fileread
{
public static File read(File f,File f1) throws FileNotFoundException
{
File file3=new File("C:\\New folder\\file3.txt");
PrintWriter output=new PrintWriter(file3);
ArrayList arr=new ArrayList();
Scanner sc=new Scanner(f);
Scanner sc1=new Scanner(f1);
while(sc.hasNext())
{
arr.add(sc.next());
}
while(sc1.hasNext())
{
arr.add(sc1.next());
}
output.print(arr);
output.close();
return file3;
}
/**
*
* #param args
* #throws FileNotFoundException
*/
public static void main(String[] args) {
try
{
File file1=new File("C:\\New folder\\file1.txt");
File file2=new File("C:\\New folder\\file2.txt");
File file3=read(file1,file2);
Scanner sc=new Scanner(file3);
while(sc.hasNext())
System.out.print(sc.next());
}
catch(Exception e)
{
System.out.printf("Error :%s",e);
}
}
}
You can do something like this in Java. Hope it helps you resolve your problem:
import java.io.*;
class FileRead {
public void readFile(String[] args) {
for (String textfile : args) {
try{
// Open the file that is the first
// command line parameter
FileInputStream fstream = new FileInputStream(textfile);
// Get the object of DataInputStream
DataInputStream in = new DataInputStream(fstream);
BufferedReader br = new BufferedReader(new InputStreamReader(in));
String strLine;
//Read File Line By Line
while ((strLine = br.readLine()) != null) {
// Print the content on the console
System.out.println (strLine);
// Write to the new file
FileWriter filestream = new FileWriter("Combination.txt",true);
BufferedWriter out = new BufferedWriter(filestream);
out.write(strLine);
//Close the output stream
out.close();
}
//Close the input stream
in.close();
}catch (Exception e){//Catch exception if any
System.err.println("Error: " + e.getMessage());
}
}
}
public static void main(String args[]) {
FileRead myReader = new FileRead();
String fileArray[] = {"file1.txt", "file2.txt", "file3.txt", "file4.txt"};
myReader.readFile(fileArray);
}
}
One liner example:
def out = new File(".all_profiles")
['.bash_profile', '.bashrc', '.zshrc'].each {out << new File(it).text}
OR
['.bash_profile', '.bashrc', '.zshrc'].collect{new File(it)}.each{out << it.text}
Tim's implementation is better if you have big files.
public static void main(String[] args) throws IOException {
List<String> files=new ArrayList<String>();
for(int i=10;i<14;i++)
files.add("C://opt/Test/test"+i+".csv");
String destFile ="C://opt/Test/test.csv";
System.out.println("TO "+destFile);
long st=System.currentTimeMillis();
mergefiles(files, destFile);
System.out.println("DONE."+(st-System.currentTimeMillis()));
}
public static void mergefiles(List<String> files,String destFile){
Path outFile = Paths.get(destFile);
try(FileChannel out=FileChannel.open(outFile, StandardOpenOption.CREATE, StandardOpenOption.WRITE)) {
for(String file:files) {
Path inFile=Paths.get(file);
System.out.println(inFile);
try(FileChannel in=FileChannel.open(inFile, StandardOpenOption.READ)) {
for(long p=0, l=in.size(); p<l; )
p+=in.transferTo(p, l-p, out);
}catch (IOException e) {
System.out.println("ERROR:: "+e.getMessage());
}
out.write(ByteBuffer.wrap("\n".getBytes()));
}
} catch (IOException e) {
System.out.println("ERROR:: "+e.getMessage());
}
}