I'm having trouble correctly receiving keyboard input in Java when it has accented characters. For example, I'm trying to input something like "présenter" but it comes in as "pr?senter". I'm not sure how to fix this - I've been trying to use ISO-8859-1 encoding but I still can't get it. Here's part of my code:
Scanner scan = new Scanner(new InputStreamReader(
System.in, Charset.forName("ISO-8859-1")));
I also tried using UTF-8 but I have the same problem. Not sure what else to do! Thanks so much!!
Are you trying to output the read char sequence to console? If so, then it's wrong. Console is not able to show accented characters as well as UTF-8 encoded characters. Just try to write your input to the file (as UTF-8) and check the file then.
The following code produces the correct result:
String charset = "ISO-8859-1";
Scanner scan = new Scanner(System.in, charset);
System.out.print("Enter your text line: ");
String line = scan.next();
System.out.println("Your input: " + line);
File file = new File("out.txt");
FileOutputStream fos = new FileOutputStream(file);
fos.write(line.getBytes(charset));
fos.close();
FileReader fr = new FileReader(file);
BufferedReader br = new BufferedReader(fr);
String readLine = br.readLine();
System.out.println("Your input (loaded from file): " + readLine);
br.close();
fr.close();
The output is:
Enter your text line: présenter
Your input: présenter
Your input (loaded from file): présenter
The file content is correct. The wrong characters by "Your input" are because of local console settings, but the value in the file is correct.
Related
I need to read contents of a file as a server, and then send the read data file, for the client so the client print it out on the Client terminal.
The problem is that I can't find a way or method to read a txt file from the current directory which my java file and txt file are existed.
Please help me.
There are many ways to read text file or file in java. It depend on you to that in which format you need to pass your file content to client side.
Here are some method to reading file in java.
1. Using BufferedReader class
BufferedReader input = new BufferedReader(new FileReader(aFile));
String line = null; //not declared within while loop
while (( line = input.readLine()) != null){
String curLine = line;
//Process line
}
2.Using Apache Common IOUtils with the class IOUtils.toString() method.
FileInputStream inputStream = new FileInputStream("FILEPATH/FILENAME");
try {
String everything = IOUtils.toString(inputStream);
} finally {
inputStream.close();
}
3.Using the Scanner class in Java and the FileReader
Scanner in = new Scanner(new FileReader("FILENAME/FILEPATH"));
while (scanner.hasNextLine()){
//process each line in some way
String line = scanner.nextLine();
}
Scanner has several methods for reading in strings, numbers, etc...
4.In JAVA 7 this is the best way to simply read a textfile
new String(Files.readAllBytes(...))
or Files.readAllLines(...)
Path path = Paths.get("FILENAME");
List<String> allLines = Files.readAllLines(path, ENCODING);
Please refer this link for more onfomation.
You can use BufferedReader to read from a txt file.
BufferedReader br = new BufferedReader(new FileReader(fileName));
String line = br.readLine();
here fileName is a string that contain your absolute file name.
eg : fileName = "C:\temp\test.txt";
You can read file by using BufferedReader.
File file=new File("filepath");
BufferedReader br=new BufferedReader(new FileReader(file)); //Here you create an object of bufferedreader which file read through filereader
String data=br.readLine();
while(data!=null)
{
System.out.println(data); // Writing in the console
data=br.readLine();
}
This will taking input from file and giving output to console.If you want it write in other file then use BufferedWriter.
File out=new File("outputfilepath");
BufferedWriter bw=new BufferedWriter(new FileWriter(out));
simply us bw.write() instead of System.out.println();.
i want to write a java program to read all the text from a file but without whitespace and lines..suppose given below is all text from a file now i want to read this text and copy it to other file
var provinfo={"cdn":"//bluehost-
cdn.com","domain":"xyz.com","name":"xyz","phone":["(888) 401-4678","(801)
765-9400"],"code":"bh"};
provinfo.cdn = location.protocol + provinfo.cdn;
such that the resultant text in new file is like
varprovinfo{"cdn":"//bluehostcdn.com","domain":"xyz.com","name":"xyz","phone["(888)401-4678","(801)765-9400"],"code":"bh"};provinfo.cdn=location.protocol+provinfo.cdn;
as you can see the text is merged into single line by eliminating whitespace and lines. Thats what i want.
scanner = new Scanner(new File("D://actual.txt"));
String a = scanner.useDelimiter("\\Z").next();
String b= a.replaceAll(" ", "");
String c = b.replaceAll("[\\r\\n]+\\s+", "");
System.out.println(c);
I used this code for writing on console but using the same with fileouputstream does not working?
To eliminate the whitespace there is a very useful and overlooked function
yourString.trim()
However, it wont elimante the lines.
Try this,
Scanner scanner = new Scanner(file);
StringBuilder stringBuilder = new StringBuilder();
while (scanner.hasNext())
{
stringBuilder.append(scanner.next().replaceAll("\\s", "").replaceAll("\n", ""));
}
System.out.println(stringBuilder.toString());
This is working absolutely fine !!! with your above program.
File outputFile = new File("output.txt");
outputFile.createNewFile();
FileOutputStream fileOutputStream = new FileOutputStream(outputFile);
fileOutputStream.write(c.getBytes());
fileOutputStream.close();
// read again from disk to make sure
Scanner scanner1 = new Scanner(new File(outputFile.getAbsolutePath()));
System.out.println(scanner1.next());
output :
varprovinfo={"cdn":"//bluehost-cdn.com","domain":"xyz.com","name":"xyz","phone":["(888)401-4678","(801)765-9400"],"code":"bh"};provinfo.cdn=location.protocol+provinfo.cdn;
I'm trying to read in a file that contains unicode characters, convert those characters to their corresponding symbols and then print the resulting text to a new file. I'm trying to use StringEscapeUtils.unescapeHtml to do this but the lines are just being printed as is, with the unicode points still intact. I did a practice run by copying a single line from the file, making a string from that and then calling StringEscapeUtils.unescapeHtml on that, which works perfectly. My code is below:
class FileWrite
{
public static void main(String args[])
{
try{
String testString = " \"text\":\"Dude With Knit Hat At Party Calls Beer \u2018Libations\u2019 http://t.co/rop8NSnRFu\" ";
FileReader instream = new FileReader("Home Timeline.txt");
BufferedReader b = new BufferedReader(instream);
FileWriter fstream = new FileWriter("out.txt");
BufferedWriter out = new BufferedWriter(fstream);
out.write(StringEscapeUtils.unescapeHtml3(testString) + "\n");//This gives the desired output,
//with unicode points converted
String line = b.readLine().toString();
while(line != null){
out.write(StringEscapeUtils.unescapeHtml3(line) + "\n");
line = b.readLine();
}
//Close the output streams
b.close();
out.close();
}
catch (Exception e){//Catch exception if any
System.err.println("Error: " + e.getMessage());
}
}
}
//This gives the desired output,
//with unicode points converted
out.write(StringEscapeUtils.unescapeHtml3(testString) + "\n");
You are mistaken. Java unescapes String literals of this form at compile time when it builds them into the class file:
"\u2018Libations\u2019"
There are no HTML 3 escapes in this code. The method you have chosen is designed to unescape escape sequences of the form ‘.
You probably want the unescapeJava method.
You're strings are being both read and written using your platforms default encoding. You want to explicitly specify the character set to use as 'UTF-8':
Input stream:
BufferedReader b = new BufferedReader(new InputStreamReader(
new FileInputStream("Home Timeline.txt"),
Charset.forName("UTF-8")));
Output stream:
BufferedWriter out = new BufferedWriter(new OutputStreamWriter(
new FileOutputStream("out.txt"),
Charset.forName("UTF-8")));
Most examples out there on the web for inputting a file in Java refer to a fixed path:
File file = new File("myfile.txt");
What about a user input file from the console? Let's say I want the user to enter a file:
System.out.println("Enter a file to read: ");
What options do I have (using as little code as possible) to read in a user specified file for processing. Once I have the file, I can convert to string, etc... I'm thinking it has to do with BufferedReader, Scanner, FileInputStream, DataInputStream, etc... I'm just not sure how to use these in conjunction to get the most efficient method.
I am a beginner, so I might well be missing something easy. But I have been messing with this for a while now to no avail.
Thanks in advance.
To have the user enter a file name, there are several possibilities:
As a command line argument.
public static void main(String[] args) {
if (0 < args.length) {
String filename = args[0];
File file = new File(filename);
}
}
By asking the user to type it in:
Scanner scanner = new Scanner(System.in);
System.out.print("Enter a file name: ");
System.out.flush();
String filename = scanner.nextLine();
File file = new File(filename);
Use a java.io.BufferedReader
String readLine = "";
try {
BufferedReader br = new BufferedReader(new FileReader( <the filename> ));
while ((readLine = br.readLine()) != null) {
System.out.println(readLine);
} // end while
} // end try
catch (IOException e) {
System.err.println("Error Happened: " + e);
}
And fill the while loop with your data processing.
Regards,
Stéphane
hello fellow java developers. I'm having a very strange issue.
I'm trying to read a csv file line by line. Im at the point where Im just testing out the reading of the lines. ONly each time that I read a line, the line contains square characters between each character of text. I even saved the file as a txt file in wordpad and notepad with no change.
Thus I must be doing something stupid...
I have a csv file, standard csv file, yes a text file with commas in it. I try to read a line of text, but the text is all f-ed up and cannot find the phrase within the text.
Any advice? code below.
//open csv
File filReadMe = new File(strRoot + "data2.csv");
BufferedReader brReadMe = new BufferedReader
(new InputStreamReader(new FileInputStream(filReadMe)));
String strLine = brReadMe.readLine();
//for all lines
while (strLine != null){
//if line contains "(see also"
if (strLine.toLowerCase().contains("(see also")){
//write line from "(see also" to ")"
int iBegin = strLine.toLowerCase().indexOf("(see also");
String strTemp = strLine.substring(iBegin);
int iLittleEnd = strTemp.indexOf(")");
System.out.println(strLine.substring(iBegin, iBegin + iLittleEnd));
}
//update line
strLine = brReadMe.readLine();
} //end for
brReadMe.close();
I can only think that this is an inconsistent character encoding. Open the file in notepad, choose Save As, and select UTF-8 in the drop down for "encoding". Then add "UTF-8" as a second parameter to InputStreamReader, e.g.
BufferedReader brReadMe = new BufferedReader
(new InputStreamReader(new FileInputStream(filReadMe), "UTF-8"));
That should sort out any inconsistencies with encoding.