Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 6 years ago.
Improve this question
Suppose my text file name is "FileToUse". How do I read this file byte by byte using the read method from the FileInputStream class?
My end goal is to create a HashMap with the key as the letter (but the byte for the letter would be the key) and the value as the number of times the letter was in the text file. Any tips on how to do this would be appreciated.
Here is what you do:
First you create a file
Then, you link the file to the fileInputStream
If the file links then you assign the file contents one by one using the read() at the same time checking if it isn't the EOF. read() returns -1 for EOF
Then you process the contents into the map
File file = new File("FileToUse.txt");
FileInputStream fis = null;
try {
fis = new FileInputStream(file);
System.out.println("Total file size to read (in bytes) : "
+ fis.available());
int content;
while ((content = fis.read()) != -1) {
// process the content into the hashmap
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (fis != null)
fis.close();
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
}
Related
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 3 years ago.
Improve this question
I have a method that writes integer array into a file.
When I read it with a method that brings those ints as array it's working.
But when I try to count how many ints it says it's empty.
The same code is written on other computer systems. and it's working for him, the SAME code!
I already put the "buffer" byte array into the read method. still not working
File file = new File("/home/arad/Desktop/intFile.bin");
int[] arr = {1,2,3,4,5,6};
//exampleWriteIntegerArray(arr, file);
reverseThisFile(file);
static void reverseThisFile(File file){
File newFile = new File("/home/arad/Desktop/newIntegerFile.bin");
InputStream inputStream = null;
OutputStream outputStream = null;
int counter = 0;
System.out.println(file.length());
try {
inputStream = new FileInputStream(file);
outputStream = new FileOutputStream(file);
byte[] buffer = new byte[4];
int actuallyRead;
while((actuallyRead = inputStream.read()) != -1){
counter++;``
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}finally {
if (inputStream != null) {
try {
inputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
System.out.println(counter);
}
Is something wrong in lines (input and output files are same):
inputStream = new FileInputStream(file);
outputStream = new FileOutputStream(file); //comment this line
Name your variables better (outputFile, inputFile)... Also output stream outputStream is not closed... Try first just to print on console, ...
he uses Windows i use Ubuntu
I suspect this is the root of the difference, in conjunction with this code:
inputStream = new FileInputStream(file);
outputStream = new FileOutputStream(file);
In the first line, you're opening the existing file to read it. In the second line, you're creating a new, empty file. Should inputStream read from that empty file, or from the file that existed before you created the new one? I believe that the behaviour of Windows and Linux (and their file systems) may differ there.
I would strongly suggest that you don't do that.
Two alternative options:
Use two different files. Read from one, write to the other.
Do all the reading first, then do all the writing.
In both of these options, you never have an input and output stream to the same file at the same time... it's that part that's the recipe for problems.
Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 3 years ago.
Improve this question
I want the text file to be in a particular format which is really what I am getting at.
I am currently looking for a way to create a new text file that is created by using the values from an ArrayList. How do I create a text file that will allow me to have the format that I am looking for?
public static void createTextFileFromArrayList() {
List<String> cities = new ArrayList<String>();
cities.addAll(Arrays.asList("Boston", "Washington", "Irving", "Dallas"));
//Get the file reference
Path path = Paths.get("C:\\apps\\output.txt");
//Use try-with-resource to get auto-closeable writer instance
try (BufferedWriter writer = Files.newBufferedWriter(path)) {
cities.forEach(city -> {
try {
writer.write(city);
writer.write("\n");
} catch (IOException e) {
e.printStackTrace();
}
});
} catch (IOException e) {
e.printStackTrace();
}
}
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 7 years ago.
Improve this question
I am trying to make a stream, so I can read 2 lines from .txt file to two string variables. I tried try/catch, but still have an ureported exception error.
public class Shad1 {
public void myMethod()throws FileNotFoundException {
String stringName = new String("");
String stringNumb = new String("");
File file = new File ("c:\\input.txt");
try {
DataInputStream input = new DataInputStream(new FileInputStream(file));
int check = input.read();
char data = input.readChar();
while(data != '\n') {
stringName = stringName + data;
}
while (check != -1){
stringNumb = stringNumb + data;}
input.close();
} catch (FileNotFoundException fnfe){System.out.println(fnfe.getMessage());}
}
you're using the read method: note that this method can also throw an IOException. See the docs for the read method here, the declaration is:
public final int read(byte[] b) throws IOException
So you'll also need to catch IOException, or report that your method throws IOException.
Note that you don't need to do both, so in your example code, you can similarly choose to report that your method throws FileNotFoundException or declare it in a catch block: you don't need both (unless some other part of the code in the method might generate an unhandled FileNotFoundException).
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 years ago.
Improve this question
I have this method which receive as parameters pdfText(which is a String containing text from a pdf file after parsing) and fileName which is the file where i want to write that text
But now I need to find the word "Keywords" in this text and extract only the words after it,which are in the same line(until the newline character).
For example I have one text which contains somewhere the following line
Title:Something.
"Keywords : Computers, Robots, Course"
Tags:tag1,tag2,tag3.
And the result should be the following list ["Computers","Robots", "Course"].
Solved Question
So I've searched how to solve my question..here is a solution,not very smart but it works:
//index of first appearence of the word
int index = pdfText.indexOf("Keywords");
//string from that to the end
String subStr = pdfText.substring(index);
//index of first appearence of the new line in the new string
int index1 = subStr.indexOf("\n");
//the string we need
String theString = subStr.substring(9,index1);
System.out.println(theString);
//write in the file..use true as parameter for appending text,not overwrite it
FileWriter pw = new FileWriter(fileName,true);
pw.write(theString);
pw.close();
Honestly, this question is too situation specific. Regardless :)
Writing to file
String pdfText = "pdfText";
String fileLocation = "fileLocation";
Writer writer = null;
try {
writer = new BufferedWriter(new OutputStreamWriter(
new FileOutputStream(fileLocation), "utf-8"));
writer.write(pdfText); // String you want to write (i.e. pdfText)
} catch (IOException ioe) {
ioe.printStackTrace();
} finally {
try {writer.close();} catch (Exception ex) { ex.printStackTrace(); }
}
It's always a good idea to specify the encoding type. ("utf-8"). It might not matter for your assignment though. You might also need to append to the file, and not re-write it completely, in which case, you should use a different constructor for the FileOutputStream, new FileOutputStream(getFileLocation(), true) . As for the many try/catch blocks, don't follow my example. It's how I manage to close my resource, as eclipse recommends haha.
Parsing the String
If you have a line such as "Keywords : Computers, Robots, Course",
String str = "Keywords : Computers, Robots, Course";
String[] array = str.substring(indexOf(':') + 1).split(",");
//this array = ["Computers", "Robots", "Course"]
Now you have an array which you can loop through and write/print out however you'd like.
You could use regex to extract the words after the word "Keyword:" like this :
String regex = ".*Keywords\\s*:(.*)\\n.*";
String extractedLine = yourText.replaceAll( regex, "$1" );
System.out.println( extractedLine );
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 8 years ago.
Improve this question
Why I am getting extra char while writing into file for the following code? If I am using writeBytes(String) than the below code is working file. Then what is the problem with dos.writeChars() method?
File fileObj = new File("student.txt");
try {
// writing into file
FileOutputStream fos = new FileOutputStream(fileObj);
String msg = "This is student file";
DataOutputStream dos = new DataOutputStream(fos);
dos.writeChars(msg);
//reading from file
FileInputStream fis = new FileInputStream(fileObj);
DataInputStream dis = new DataInputStream(fis);
System.out.println(dis.readLine());
for (int i = 0; ((i = dis.read()) != -1); i++) {
System.out.println(i);
}
fos.close();
dos.close();
} catch (FileNotFoundException e) {
System.err.println("File not found!");
} catch (IOException e) {
e.printStackTrace();
}
writeChars() uses 2-byte chars (UTF-16). So each char you write will result in two bytes written.
If you want another encoding use getBytes() on the String and write it as bytes.