Java reading file and storing text as array - java

I wrote a program someone told me to do for reading file and storing the text as an array, but when I run the program, I get an error that looks like this:
run:
Exception in thread "main" java.io.FileNotFoundException: KeyWestTemp.txt (No such file or directory)
at java.io.FileInputStream.open(Native Method)
at java.io.FileInputStream.<init>(FileInputStream.java:146)
at java.util.Scanner.<init>(Scanner.java:656)
at HeatIndex.main(HeatIndex.java:32)
Java Result: 1
BUILD SUCCESSFUL (total time: 0 seconds)
I want to have my program display the array to make sure it works correctly. Any help would be greatly appreciated.
Below is the program code:
import java.util.Scanner;
import java.io.File;
import java.io.IOException;
import java.util.LinkedList;
import java.util.List;
public class HeatIndex {
/**
* #param args the command line arguments
* #throws java.io.IOException
*/
public static void main(String[] args) throws IOException{
// TODO code application logic here
// // read KeyWestTemp.txt
// create token1
String token1 = "";
// create Scanner inFile1
Scanner inFile1 = new Scanner(new File("KeyWestTemp.txt")).useDelimiter(",\\s*");
// create List
List<String> temps = new LinkedList<String>();
// while loop
while(inFile1.hasNext()){
// find next line
token1 = inFile1.next();
// initialize temps
temps.add(token1);
}
// close inFile1
inFile1.close();
// create array
String[] tempsArray = temps.toArray(new String[0]);
// for-each loop
for(String s : tempsArray){
// display s to make sure program works correctly
System.out.println(s);
}
}
}

Your program is unable to locate your file. Make sure the file is in your working directory, or change new File("KeyWestTemp.txt") to provide a complete path (e.g. C:/Users/...../KeyWestTemp.txt).

Apparently, the file KeyWestTemp.txt is not found by the Java program. The most likely problem is that you haven't placed it in the right place.
You have 2 options:
Place the file in the working directory, from where you run the java command
When initializing the Scanner, set the full path: new Scanner(new File("/file/path/to/KeyWestTemp.txt")) to the file

Two ways to fix it:
Put your txt file in the same dir of your Java program.
Write the full path of the txt file (c:/files...). Remember to use File.separator instead of the "/" or "\" to make the program platform independent.

Related

Create new file with the contents of a string array taken from another file using methods (Java)

I am writing some code that takes each line of a txt file and stores it into a string. Afterward, the program will make a new file and store write the array into it.
This is the contents of the file:
04/26/16 Sega 3D Classics Collection
07/14/16 Batman: Arkham Underworld
06/24/16 Tokyo Mirage Sessions #FE
The problem with my code is that it doesn't seem to store or make a new file once the method is running. The method to make the file into a string array works but it doesn't seem to take that array and write it on a brand new file. What I have tried is to use the FileWriter function to make a new file on my computer and use the writer function to write the array onto the file. Whenever I run or debug the program there is no new file in my computer.
This is the code I have:
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Scanner;
public class Main{
public static void main (String[]args) throws FileNotFoundException{
File file = new File("releasedates.txt");
input(file);
}
public static String[]input (File file) throws FileNotFoundException{
String[]arr = new String[3];
Scanner sc = new Scanner(file);
for(int i = 0; i < arr.length; i++){
arr[i] = sc.nextLine();
}
return arr;
}
public static void output(String filename, String[] info) throws IOException{
FileWriter writer = new FileWriter("fileName.txt");
writer.write(filename);
writer.close();
}
}
If you're hoping that running your main() method will read and write back out the contents of the file I'm seeing the following things that are preventing you from having the result you're looking for:
Your main() never calls the output() method that actually writes to the file.
Your output() method will write the value of fileName to the file, not the value of the info array that you pass in. You may have to call Arrays.toString(info) or iterate through its contents so the FileWriter can process it correctly.

Printing a Specified File Exercise Java

Taking a beginners course in Java and I am stuck on one of the exercises. We're meant to print the text within a specific file, which we can find via the file's name which was inputted by a user. In our previous exercise, we learned that
try(Scanner scanner = new Scanner(Paths.get("data.txt")))
would find the text within the file "data.txt", but I am unsure about how to convert this into finding any file name inputted by the user.
More details below.
Exercise: Write a program that asks the user for a string, and then prints the contents of a file with a name matching the string provided. You may assume that the user provides a file name that the program can find.
The exercise template contains the files "data.txt" and "song.txt", which you may use when testing the functionality of your program. The output of the program can be seen below for when a user has entered the string "song.txt". The content that is printed comes from the file "song.txt". Naturally, the program should also work with other filenames, assuming the file can be found.
My code so far is:
import java.nio.file.Paths;
import java.util.Scanner;
public class PrintingASpecifiedFile {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("Which file should have its contents printed?");
String fileName = scanner.nextLine();
//try(Scanner scanner = new Scanner(Paths.get(fileName))) {
try(scanner = Paths.get(fileName)) { // this part of the code is underlined red
while (scanner.hasNextLine()){
String output = scanner.nextLine();
System.out.println(output);
}
}
catch (Exception e){
System.out.println("Error: " + e.getMessage());
}
}
}
I have tried searching how to add a new scanner as that was a suggestion but every time I've tried it gets an error. Also the "try" section is underlined red and cannot seem to figure out why. The underlined red part says variables in try-with-resources are not supported in -source 8
If anyone has tips, I would really appreciate it! Thank you!
You used one Scanner for reading the file path from the console.
You need an other Scanner (or reader alternative) for reading the file.
try (Scanner fileScanner = new Scanner(fileName)) {
try (Scanner fileScanner = new Scanner(Paths.get(fileName))) {

Replace Pattern match with Preferred Text Java

Hey I am trying to replace the a regex pattern in a directory of files and replace with this character 'X'. I started out trying alter one file but that is not working. I cam eup with the following code any help would be appreciated.
My goal is to read all the file content find the regex pattern and replace it.
Also this code is not working it runs but dose nothing to the text file.
import java.io.File;
import java.io.IOException;
import org.apache.commons.io.FileUtils;
public class DataChange {
public static void main(String[] args) throws IOException {
String absolutePathOne = "C:\\Users\\hoflerj\\Desktop\\After\\test.txt";
String[] files = { "test.txt" };
for (String file : files) {
File f = new File(file);
String content = FileUtils.readFileToString(new File(absolutePathOne));
FileUtils.writeStringToFile(f, content.replaceAll("2018(.+)", "X"));
}
}
}
File Content inside the file is:
3-MAAAA2017/2/00346
I am trying to have it read through and replace 2017/2/00346 with XXX's
my goal is to do this for like 3 files at one time also.

OCR implementation using using java

I have written java code to convert images into text using java.But my code is taking only single image as input . I want that the program should fetch images from a folder and then run the OCR on it.
My code is:
import java.io.FileOutputStream;
import org.bytedeco.javacpp.*;
import org.junit.Test;
import static org.bytedeco.javacpp.lept.*;
import static org.bytedeco.javacpp.tesseract.*;
import static org.junit.Assert.assertTrue;
import java.io.File;
public class BasicTesseractExampleTest {
#Test
public void givenTessBaseApi_whenImageOcrd_thenTextDisplayed() throws Exception {
BytePointer outText;
TessBaseAPI api = new TessBaseAPI();
// Initialize tesseract-ocr with English, without specifying tessdata path
if (api.Init(".", "ENG") != 0) {
System.err.println("Could not initialize tesseract.");
System.exit(1);
}
PIX image = pixRead("IMG_0012 (1).jpg");
api.SetImage(image);
// Get OCR result
outText = api.GetUTF8Text();
String string = outText.getString();
assertTrue(!string.isEmpty())
System.out.println(str);
// Destroy used object and release memory
api.End();
outText.deallocate();
pixDestroy(image);
}
}
To read a list of files out of a given Path use for example:
File f = new File("C:/programs");
File[] fileArray = f.listFiles();
Now you can check every File out of the fileArray if it is a directory and skip that with:
if(fileArray[0].isDirectory()) continue;
To find the images you can check for example the ending of the filename with:
fileArray[0].getName().endsWith(".jpg")
Do this check for all files out ouf the fileArray and call your method with the right files. To check the right file you have to change this line of your code:
PIX image = pixRead("IMG_0012 (1).jpg");
and add the fileArray[?] where the ? must be replaced with the right number.

How to write a method that accesses the system?

My program is almost working but the second array in my main isn't displaying anything. I can't figure out why. Here is my code.
package myutilites;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Map;
import java.util.Scanner;
import java.util.StringTokenizer;
public class extraCredit
{
public static void main(String args [])
{
ArrayList<String> array = system("ls -l");
for(String s: array)
System.out.println(s);
ArrayList<String> array1 = system("ls -l *.java");
for(String a: array1)
System.out.println(a);
}
public static ArrayList<String> system(String string)
{
ArrayList<String> array = new ArrayList<String>();
ArrayList<String> infoArray = new ArrayList<String>();
String s = string;
StringTokenizer tok = new StringTokenizer(s,"\\,: ");
while(tok.hasMoreTokens())
{
array.add(tok.nextToken());
}
for (String a : array)
System.out.println(a);
try
{
ProcessBuilder pb = new ProcessBuilder(array);
Map<String, String> env = pb.environment();
env.put("VAR1", "myValue");
env.remove("OTHERVAR");
env.put("VAR2", env.get("VAR1") + "suffix");
pb.directory();
Process p = pb.start();
Scanner c = new Scanner(p.getInputStream());
while(c.hasNext())
{
infoArray.add(c.nextLine());
}
c.close();
} catch (IOException e) {}
return infoArray;
}
}
my output is this. the ls -l *.java doesn't work.
ls
-l
total 0
drwxr-xr-x 8 brianhammons staff 272 Sep 10 09:44 bin
drwxr-xr-x 10 brianhammons staff 340 Sep 9 10:04 src
ls
-l
*.java
Your input string "ls -l .java" will not return anything unless you are in the directory containing Java source code. As it is, it is looking for a directory ".java" which cannot be found. You need to pass in the full path into the system function
It depends what you are trying to do. If you want to find every *.java file on your system then use: "locate *.java".
This will find every instance of a file or directory with "java" in the name icluding source code and system file. Use "locate --help" to find a list of options to use with the locate command.
If you want to find just you source code then you will need to loop through the directory structure looking for your source directories (normally src) and then extract the files.
If you just want to search one specific directory then you must use the command: "cd ".
EG cd /home/michael/Java.
It would help to learn some basic Bash commands. One of the best sources is http://bash.cyberciti.biz/guide/Main_Page.
If you can be more specific about what you are trying to do I would be happy to help
I like using Java to do systems work (I know, it's a bit odd, but that's just me). However, in your case, I would highly recommend not using it for this task.
Java already has an excellent ability to access the file system details, through the File, Path, and FileSystem interfaces. Unless you really need something that is truly exotic, you'll get better results through those interfaces than the results you can hand parse and put together yourself.

Categories