I have a data structure assignment were the code has to read the text data from a text file and print it onto the screen. The code that I wrote says that the build was a success but the text file itself doesn't print. What do I do?
import java.util.Scanner;
import java.io.IOException;
import java.io.FileInputStream
public class readFile{
public static void main(String[] args) throws IOException {
FileInputStream fileByteStream = null;
Scanner file = null;
int textFile;
try{
fileByteStream = new FileInputStream("file1.txt");
file = new Scanner(fileByteStream);
while(file.hasNextInt()){
textFile = file.nextInt();
System.out.println("file1.txt");
}
}
catch(IOException e){
}
}
}
Replace System.out.println("file1.txt"); by System.out.println(textFile);.
This should work if you have the "file1.txt" saved in the correct location. As is, you are just passing the String "file1.txt" rather than the file object which was not yet created. (See line 13 of this code below)
import java.util.Scanner;
import java.io.IOException;
import java.io.File;
import java.io.FileInputStream;
public class readFile
{
public static void main(String[] args) throws IOException
{
FileInputStream fileByteStream = null;
Scanner file = null;
int textFile;
File file1 = new File("file1.txt");
try
{
fileByteStream = new FileInputStream(file1);
file = new Scanner(fileByteStream);
System.out.println("Reading file...");
while(file.hasNextInt())
{
textFile = file.nextInt();
System.out.println(textFile);
System.out.println("Scanning a line..");
}
file.close();
}
catch(IOException e)
{
System.out.println("Exception handled");
e.printStackTrace();
}
}
}
You can use print statements to help see where the code is breaking. It looks like you have an IO Exception (input/output). Also, you should want to close the Scanner object.
import java.util.Scanner;
import java.io.IOException;
import java.io.FileInputStream;
public class readFile
{
public static void main(String[] args) throws IOException
{
FileInputStream fileByteStream = null;
Scanner file = null;
int textFile;
try
{
fileByteStream = new FileInputStream("file1.txt");
file = new Scanner(fileByteStream);
System.out.println("Reading file...");
while(file.hasNextInt())
{
textFile = file.nextInt();
System.out.println(textFile);
System.out.println("Scanning a line..");
}
file.close();
}
catch(IOException e)
{
System.out.println("Exception handled");
}
}
}
Related
I have a file called "ParkPhotos.txt" and inside I have 12 names of some parks, for example "AmericanSamoa1989_photo.jpg". I want to replace the "_photo.jpg" to "_info.txt", but I am struggling. In the code I was able to read the file, but I am not sure how to replace it.
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Scanner;
public class FileNameChange {
public static void main(String[] args) throws IOException
{
readFileValues();
}
public static void readFileValues() throws IOException
{
try {
File aFile = new File("ParkPhotos.txt");
Scanner inFile = new Scanner(aFile);
while (inFile.hasNextLine())
{
String parkNames = inFile.nextLine();
System.out.println(parkNames);
}
inFile.close();
} catch (FileNotFoundException e)
{
System.out.println("An error has occurred");
e.printStackTrace();
}
}
}
You can convert to a new content and write it to the current file. For example:
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;
import java.net.URISyntaxException;
import java.net.URL;
import java.util.Scanner;
public class FileNameChange {
public static void main(String[] args) throws URISyntaxException {
String newContent = readFileValues();
writeFileValues(newContent);
}
public static String readFileValues() {
StringBuilder newContent = new StringBuilder();
try {
URL url = FileNameChange.class.getClassLoader().getResource("ParkPhotos.txt");
File aFile = new File(url.toURI());
Scanner inFile = new Scanner(aFile);
while (inFile.hasNextLine()) {
String parkName = inFile.nextLine();
if (parkName == null || parkName.isEmpty()) {
continue;
}
newContent.append(parkName.replace("_photo.jpg", "_info.txt"))
.append(System.lineSeparator());
}
inFile.close();
} catch (FileNotFoundException | URISyntaxException e) {
e.printStackTrace();
}
return newContent.toString();
}
public static void writeFileValues(String content) throws URISyntaxException {
URL url = FileNameChange.class.getClassLoader().getResource("ParkPhotos.txt");
File aFile = new File(url.toURI());
try (FileWriter writer = new FileWriter(aFile)) {
writer.write(content);
} catch (IOException e) {
e.printStackTrace();
}
}
}
Note: the file will be written at build folder. For example: example_1/build/resources/main
I made this homework exercise to read text from a text file and store it reversed into another new file. This is the code:
import java.util.*;
import java.io.*;
public class FileEcho {
File file;
Scanner scanner;
String filename = "words.txt";
File file1 ;
PrintWriter pw ;
void echo() {
try {
String line;
file = new File( filename);
scanner = new Scanner( file );
file1 = new File("brabuhr.txt");
pw = new PrintWriter(file1);
while (scanner.hasNextLine()) {
line = scanner.nextLine();
String s = new StringBuilder(line).reverse().toString();
pw.println(s);
}
scanner.close();
} catch(FileNotFoundException e) {
System.out.println( "Could not find or open file <"+filename+">\n"+e
);
}
}
public static void main(String[] args) {
new FileEcho().echo();
}
}
and here is a picture Picture here
The question is: why is the newly generated file decreased in size despite having the same characters but reversed?
Would be great if someone can explain it because even my professor didn't know why is that.
P.S; the context of the file is just some words from the dictionary.
Also in other students computers so the problem is not from my computer
The problem is that you never closed the output stream pw, so that any pending output isn't written to the underlying file. This may cause truncation of your file.
You should have closed the output stream with pw.close() in a finally, or in a try with resources.
try (pw = new PrintWriter(file1)) {
while (scanner.hasNextLine()) {
line = scanner.nextLine();
String s = new StringBuilder(line).reverse().toString();
pw.println(s);
}
}
Your implementation can be simplified to be the following:
import java.io.IOException;
import java.io.PrintWriter;
import java.nio.file.Files;
import java.nio.file.Paths;
public class FileEcho {
void echo() throws IOException {
try (PrintWriter pw = new PrintWriter("brabuhr.txt")) {
Files.lines(Paths.get("words.txt"))
.map(s -> new StringBuilder(s).reverse().toString())
.forEach(pw::println);
}
}
public static void main(String[] args) throws IOException {
new FileEcho().echo();
}
}
In this example I used a 'try-with-resources' to have the PrintWriter pw autoclosed.
I have the following code seen below, this code looks through a directory and then prints all of the different file names. Now my question is, how would I go about changing my code, so that it would also print out all of the content within the files which it finds/prints? As an example, lets say the code finds 3 files in the directory, then it would print out all the content within those 3 files.
import java.io.File;
import java.io.IOException;
public class EScan {
static String usernamePc = System.getProperty("user.name");
final static File foldersPc = new File("/Users/" + usernamePc + "/Library/Mail/V2");
public static void main(String[] args) throws IOException {
listFilesForFolder(foldersPc);
}
public static void listFilesForFolder(final File foldersPc) throws IOException {
for (final File fileEntry : foldersPc.listFiles()) {
if (fileEntry.isDirectory()) {
listFilesForFolder(fileEntry);
} else {
System.out.println(fileEntry.getName());
}
}
}
}
I tested it before posting. it is working.
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
* #author EdwinAdeola
*/
public class TestPrintAllFiles {
public static void main(String[] args) {
//Accessing the folder path
File myFolder = new File("C:\\Intel");
File[] listOfFiles = myFolder.listFiles();
String fileName, line = null;
BufferedReader br;
//For each loop to print the content of each file
for (File eachFile : listOfFiles) {
if (eachFile.isFile()) {
try {
//System.out.println(eachFile.getName());
fileName = eachFile.getAbsolutePath();
br = new BufferedReader(new FileReader(fileName));
try {
while ((line = br.readLine()) != null) {
System.out.println(line);
}
} catch (IOException ex) {
Logger.getLogger(TestPrintAllFiles.class.getName()).log(Level.SEVERE, null, ex);
}
} catch (FileNotFoundException ex) {
Logger.getLogger(TestPrintAllFiles.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
}
}
You may use Scanner to read the contents of the file
try {
Scanner sc = new Scanner(fileEntry);
while (sc.hasNextLine()) {
String s = sc.nextLine();
System.out.println(s);
}
sc.close();
} catch (Exception e) {
e.printStackTrace();
}
You can try one more way if you find suitable :
package com.grs.stackOverFlow.pack10;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.util.Arrays;
import java.util.List;
public class EScan {
public static void main(String[] args) throws IOException {
File dir=new File("C:/your drive/");
List<File> files = Arrays.asList(dir.listFiles(f->f.isFile()));
//if you want you can filter files like f->f.getName().endsWtih(".csv")
for(File f: files){
List<String> lines = Files.readAllLines(f.toPath(),Charset.defaultCharset());
//processing line
lines.forEach(System.out::println);
}
}
}
Above code can me exploited in number of ways like processing line can be modified to add quotes around lines as below:
lines.stream().map(t-> "'" + t+"'").forEach(System.out::println);
Or print only error messages lines
lines.stream().filter(l->l.contains("error")).forEach(System.out::println);
Above codes and variations are tested.
I am trying to create a file from a log report. To save the file I've created a button. When the button is pushed, the following code is executed:
public void SAVE_REPORT(KmaxWidget widget){//save
try {
String content = report.getProperty("TEXT");
File file = new File("logKMAX.txt");
// if file doesnt exists, then create it
if (!file.exists()) {
file.createNewFile();
}
FileWriter fw = new FileWriter(file.getAbsoluteFile());
BufferedWriter bw = new BufferedWriter(fw);
bw.write(content);
bw.close();
} catch (IOException e) {
e.printStackTrace();
}
} //SAVE_REPORT
I have no compilation errors, but there isn't any file saved.
Any idea on what might be wrong?
Use the new file API. For one, in your program, you don't verify the return value of .createNewFile(): it doesn't throw an exception on failure...
With the new file API, it is MUCH more simple:
public void saveReport(KmaxWidget widget)
throws IOException
{
final String content = report.getProperty("TEXT");
final Path path = Paths.get("logKMAX.txt");
try (
final BufferedWriter writer = Files.newBufferedWriter(path,
StandardCharsets.UTF_8, StandardOpenOption.CREATE);
) {
writer.write(content);
writer.flush();
}
}
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.nio.file.Files;
import java.nio.file.StandardCopyOption;
public class moveFolderAndFiles
{
public static void main(String[] args) throws Exception
{
File sourceFolder = new File("c:\\Audio Bible");
copyFolder(sourceFolder);
}
private static void copyFolder(File sourceFolder) throws Exception
{
File files[] = sourceFolder.listFiles();
int i = 0;
for (File file: files){
if(file.isDirectory()){
File filter[] = new File(file.getAbsolutePath()).listFiles();
for (File getIndividuals: filter){
System.out.println(i++ +"\t" +getIndividuals.getPath());
File des = new File("c:\\audio\\"+getIndividuals.getName());
Files.copy(getIndividuals.toPath(), des.toPath(), StandardCopyOption.REPLACE_EXISTING);
}
}
}
}
}
I'm writing a little program that just takes a file, and trims the last 4 characters after a space and writes those to a new file. When I tell it to do this and then print them to console it works fine. They show up fine and everything works. But when I use the BufferedWriter to write it to a new file it gives me a weird string of characters in that file when I check it. Here is my code:
package trimmer;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Scanner;
public class trimmer {
private File file;
private File newfile;
private Scanner in;
public void Create() {
String temp, temp1;
try {
setScanner(new Scanner(file));
} catch (FileNotFoundException e) {
System.out.println("file not found!!");
}
if (!newfile.exists()) {
try {
newfile.createNewFile();
FileWriter fw = new FileWriter(newfile.getAbsoluteFile());
BufferedWriter bw = new BufferedWriter(fw);
while (in.hasNextLine()) {
temp1 = in.nextLine();
temp = temp1.substring(temp1.lastIndexOf(' ') + 1);
System.out.println(temp);
bw.write(temp);
}
bw.close();
System.out.println("done!");
} catch (IOException e) {
System.out.println("Could not make new file: " + newfile + " Error code: " + e.getMessage());
}
}
}
public Scanner getScanner() {
return in;
}
public void setScanner(Scanner in) {
this.in = in;
}
public File getFile() {
return file;
}
public void setFile(File file) {
this.file = file;
}
public File getNewfile() {
return newfile;
}
public void setNewfile(File newfile) {
this.newfile = newfile;
}
}
and when I check the file it looks like this:
䐳噔吳商吳啍唳噎吳剄唳剄䘳剄唳噎吳商䠳卉䌳䕎䜳䱁䠳卉䴳㉕倳乓䐳䍐䐳啐吳䍖吳乓吳啍䔳䥘䌳噔匳剕唳乓唳䅍䌳䕎䜳䱁䴳㉕倳乓䐳䍐䐳啐吳䍖䠳卉吳乓吳啍䔳䥘䌳噔匳剕唳乓唳䅍
Can anyone tell me why this would be happening?
FileWriter uses the platform default character encoding. If this is not the encoding that you want, then you need to use an OutputStreamWriter with the appropriately chosen character encoding.